diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
new file mode 100644
index 000000000..f97e000e2
--- /dev/null
+++ b/.github/workflows/main.yml
@@ -0,0 +1,34 @@
+on:
+ schedule:
+ - cron: '0 7 * * *'
+
+ workflow_dispatch:
+
+
+jobs:
+ sync_with_upstream:
+ runs-on: ubuntu-latest
+ name: Sync main with upstream latest
+
+ steps:
+ - name: Checkout main
+ uses: actions/checkout@v2
+ with:
+ ref: master
+ fetch-depth: 0
+
+ - name: Pull (Fast-Forward) upstream changes
+ id: sync
+ uses: aormsby/Fork-Sync-With-Upstream-action@v2.3
+ with:
+ upstream_repository: bhoffman0/CSAwesome
+ upstream_branch: master
+ target_branch: master
+
+ - name: Check for new commits
+ if: steps.sync.outputs.has_new_commits
+ run: echo "There were new commits."
+
+ # Step 4: Print a helpful timestamp for your records (not required, just nice)
+ - name: Timestamp
+ run: date
diff --git a/.gitignore b/.gitignore
index 9cdf32ac5..9bd3cb7b7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,13 +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
-pavement.py
-sphinx_settings.json
-pavement.py
-pavement.py
+.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
index ced024207..6f30d12c6 100644
--- a/CodeTestHelper.java
+++ b/CodeTestHelper.java
@@ -2,6 +2,8 @@
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;
@@ -10,24 +12,44 @@
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.*;
+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.
+ * 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 0.2.9
- * @since 2020-07-10
- *
- *
+ * @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 class CodeTestHelper {
public static boolean replit = false;
private static String results = "";
@@ -39,23 +61,26 @@ public class CodeTestHelper
private final double DEFAULT_ERROR = 0.005;
-/* Constructors -----------------------------------------------------------------*/
+ /*
+ * Constructors
+ * -----------------------------------------------------------------
+ */
public CodeTestHelper() {
String name = findMainMethod();
setupClass(name);
}
-
+
public CodeTestHelper(String name) {
setupClass(name);
}
- public CodeTestHelper(String name, String input){
+ public CodeTestHelper(String name, String input) {
inContent = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
System.setIn(inContent);
-
+
setupClass(name);
-
+
System.setIn(System.in);
}
@@ -65,52 +90,66 @@ private void setupClass(String name) {
this.className = name;
this.c = Class.forName(this.className);
- mainOutput = getMethodOutput("main");
+ if (mainOutput.equals("")) {
+ mainOutput = getMethodOutput("main");
+ }
} catch (Exception e1) {
try {
name = findMainMethod();
- if (!name.equals("main not found")){
+ if (!name.equals("main not found")) {
this.className = name;
this.c = Class.forName(this.className);
- mainOutput = getMethodOutput("main");
- }
- else {
+ 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");
-/* Output and Formatting Methods -----------------------------------------*/
+ } 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.
+ * 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.
- *
+ * 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--------------------------------------------------------";
+ 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";
@@ -119,16 +158,17 @@ public static String getFinalResults() {
}
/**
- * 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
+ * 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)
- {
+ public boolean getResults(String expected, String actual, String msg) {
return getResults(false, false, expected, actual, msg);
}
@@ -143,19 +183,22 @@ public boolean getResultsRegEx(String expected, String actual, String 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)
- {
+
+ 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 (useRegex)
- passed = isMatch(actual, expected);
- if (!passed && contain)
- passed = containsMatch(actual, expected);
+ boolean passed = false;
if (!passed && !contain) {
String clnExp = cleanString(expected);
@@ -164,143 +207,199 @@ public boolean getResults(boolean useRegex, boolean contain, String expected, St
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 = clnExp.contains(clnAct);
+ passed = clnAct.contains(clnExp);
}
String output = formatOutput(expected, actual, msg, passed);
results += output + "\n";
- //System.out.println(output);
+ // 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
+ * 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)
- {
+ public boolean getResults(String expected, String actual, String msg, boolean pass) {
String output = formatOutput(expected, actual, msg, pass);
results += output + "\n";
- //System.out.println(output);
-
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)
+ * 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)
- {
+ 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)
+ * 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)
- {
+ 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);
+ String output = formatOutput(String.format("%.5f", expected), String.format("%.5f", actual), msg, passed);
results += output + "\n";
- //System.out.println(output);
+ // System.out.println(output);
return passed;
}
- private String formatOutput(String expected, String actual, String msg, boolean 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";
+ // 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", "
");
+ 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;
+ // return "Expected: " + expected + " Actual: " + actual + " Message: " + msg +
+ // " Passed: " + passed;
}
-/* Get Method output code --------------------------------------------------------*/
+ /*
+ * 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 ????
+ * 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
+ * @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 String[1]);
+ 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
+ * 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
+ * @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 + "... ");
+ // 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")) {
+ 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);
+ return getInstanceMethodOutput(methodName, args);
}
}
- }
+ }
if (errorMessage.equals(""))
errorMessage = "Method " + methodName + " does not exist (2)";
@@ -313,7 +412,10 @@ public String getMethodOutput(String methodName, Object[] args) {
return errorMessage;
}
-/* Class Testing Methods ---------------------------------------------------------*/
+ /*
+ * Class Testing Methods
+ * ---------------------------------------------------------
+ */
private Object o;
Method[] methods;
@@ -327,17 +429,17 @@ private String getInstanceMethodOutput(String methodName)// throws IOException
private String getInstanceMethodOutput(String methodName, Object[] args)// throws IOException
{
- //System.out.println("Testing Method " + methodName + "... ");
+ // System.out.println("Testing Method " + methodName + "... ");
errorMessage = "";
try {
methods = c.getDeclaredMethods();
- for(Method m: methods) {
- if(m.getName().equals(methodName)) {
+ for (Method m : methods) {
+ if (m.getName().equals(methodName)) {
- if(!checkStaticMethod(m) && checkReturnType(m, "void")) {
- return getInstanceMethodOutput(m, null);
+ if (!checkStaticMethod(m) && checkReturnType(m, "void")) {
+ return getInstanceMethodOutput(m, args);
} else if (!checkStaticMethod(m)) {
Object o = getTestInstance();
@@ -348,11 +450,11 @@ private String getInstanceMethodOutput(String methodName, Object[] args)// throw
Object result = m.invoke(o, args);
return cleanResult(result);
} else {
- errorMessage = "Method not static or not void (4)";
+ errorMessage = "Method not static or not void (4)";
}
}
- }
+ }
if (errorMessage.equals(""))
errorMessage = "Method does not exist (4)";
@@ -365,10 +467,10 @@ private String getInstanceMethodOutput(String methodName, Object[] args)// throw
return errorMessage;
}
- private String cleanResult(Object result) {
- //System.out.println(result.getClass().getComponentType().isArray());
+ protected String cleanResult(Object result) {
+ // System.out.println(result.getClass().getComponentType().isArray());
- if (result.getClass().isArray() ){
+ if (result.getClass().isArray()) {
if (result.getClass().getComponentType().isArray()) {
String output = "[";
Object[][] array = (Object[][]) result;
@@ -400,15 +502,12 @@ private String cleanResult(Object 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 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 {
@@ -434,11 +533,10 @@ private String getInstanceMethodOutput(Method m, Object[] args)// throws IOExcep
String output = outContent.toString();
cleanUpStreams();
return output.trim();
- }
- catch(Exception e) {
+ } catch (Exception e) {
if (errorMessage.equals(""))
errorMessage = stackToString(e);
- //errorMessage = "Method could not be invoked (5)";
+ // errorMessage = "Method could not be invoked (5)";
}
if (errorMessage.equals(""))
@@ -448,45 +546,53 @@ private String getInstanceMethodOutput(Method m, Object[] args)// throws IOExcep
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
- *
+ * 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){
+ 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);
+ 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;
+ 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;
+ 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
- *
+ * 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 <getNext method. In the constructor it will create an ArrayList and fill it by looping through the array and adding each string to the list. In the getNext method, if the list length is greater than zero, it will pick a position at random in the list and remove the item from that position and return it. Otherwise, if the list is empty, it returns "NONE". The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
getNext method. In the constructor it will create an ArrayList and fill it by looping through the array and adding each string to the list. In getNext it will return "NONE" if the length of the list is 0. Otherwise, it will calculate a random index in the list, remove the string at that index, and return it. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The mixed up code below includes the correct code for the class, an instance variable, a constructor, and the `getNext` method. In the constructor it will create an `ArrayList` and fill it by looping through the array and adding each string to the list. In `getNext` it will return "NONE" if the length of the list is 0. Otherwise, it will calculate a random index in the list, remove the string at that index, and return it. The blocks have been mixed up and include extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
public class RandomStringChooser
{
/* fields */
- private Listreturn(a[1]*= 2);.
:feedback_b: This would be true if the return statement was return (a[0]*=2);.
- :feedback_c: This would be true if it was a[0]--; Or it would be true if array indicies started at 1, but they start with 0.
+ :feedback_c: This would be true if it was a[0]--; Or it would be true if array indices started at 1, but they start with 0.
:feedback_d: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to a 2. The return (a[1] * 2) does not change the value at a[1].
- :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent.
+ :feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; So the 3 will become a 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent.
Consider the following method and if ``int[] a = {8, 3, 1}``, what is the value in ``a[1]`` after ``m1(a);`` is run?
-
+
.. code-block:: java
-
+
public int m1(int[] a)
{
a[1]--;
return (a[1] * 2);
}
-
+
.. mchoice:: pe1_15
:answer_a: a = 6 and b = 7
- :answer_b: a = 6 and b = 13
- :answer_c: a = 13 and b = 0
- :answer_d: a = 6 and b = 0
+ :answer_b: a = 6 and b = 13
+ :answer_c: a = 13 and b = 0
+ :answer_d: a = 6 and b = 0
:answer_e: a = 0 and b = 13
:correct: c
- :feedback_a: This would be true if the loop stopped when i was equal to 6.
+ :feedback_a: This would be true if the loop stopped when i was equal to 6.
:feedback_b: Actually i = 6 and t = 6 and a = 13 after the loop finishes.
:feedback_c: The variable i loops from 1 to 6 else if ((num2<0) || (num1<0)) is executed and this will be true since num2 is less than 0 and for a complex conditional joined with Or (||) only one of the expressions must be true for it to execute.
- :feedback_d: This will not happen since if num2 is less than 0 the previous conditional would be true ((num2<0) || (num1<0))((num2<0) || (num1<0))((num2<0) || (num1<0))).
+ :feedback_e: This will not happen since if num2 is less than 0 the previous conditional would be true ((num2<0) || (num1<0))).
Consider the following method. What is the output from ``conditionTest(3,-2);``?
-
+
.. code-block:: java
public static void conditionTest(int num1, int num2)
{
- if ((num1 > 0) && (num2 > 0)) {
+ if ((num1 > 0) && (num2 > 0))
+ {
if (num1 > num2)
System.out.println("A");
else
System.out.println("B");
}
- else if ((num2 < 0) || (num1 < 0)) {
+ else if ((num2 < 0) || (num1 < 0))
+ {
System.out.println("C");
}
- else if (num2 < 0) {
+ else if (num2 < 0)
+ {
System.out.println("D");
}
- else {
+ else
+ {
System.out.println("E");
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/_sources/TimedTests/test3.rst b/_sources/TimedTests/test3.rst
old mode 100755
new mode 100644
index 33ef73033..7a04dd8c3
--- a/_sources/TimedTests/test3.rst
+++ b/_sources/TimedTests/test3.rst
@@ -1,42 +1,42 @@
.. qnum::
:prefix: 13-2-
:start: 1
-
+
.. |start| image:: Figures/start.png
:height: 24px
:align: top
:alt: start
-
+
.. |next| image:: Figures/next.png
:height: 24px
:align: top
:alt: next
-
+
.. |prev| image:: Figures/prev.png
:height: 24px
:align: top
:alt: previous
-
+
.. |pause| image:: Figures/pause.png
:height: 24px
:align: top
:alt: pause
-
+
.. |finish| image:: Figures/finishExam.png
:height: 24px
:align: top
:alt: finish exam
-
-Practice Exam 2 for the AP CS A Exam
+
+Practice Exam 2 for the AP CSA Exam
-------------------------------------
-The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability.
+The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability.
Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed.
-.. timed:: postexam3
+.. timed:: practiceexam2
:timelimit: 45
-
+
.. mchoice:: pe3_1
:answer_a: 10
:answer_b: 15
@@ -44,20 +44,20 @@ Click the |start| button when you are ready to begin the exam, but only then as
:answer_d: 12
:answer_e: 22
:correct: c
- :feedback_a: This would be true if it was adding up all the values in the third column, the one at index 2.
+ :feedback_a: This would be true if it was adding up all the values in the third column, the one at index 2.
:feedback_b: This would be true if it was adding up all the values in the first column, the one at index 0.
- :feedback_c: This code adds up all the values in the second column, the one at index 1 since column indicies start at 0.
- :feedback_d: This would be true if it was adding up all the values in the last column, the one at index 3.
+ :feedback_c: This code adds up all the values in the second column, the one at index 1 since column indices start at 0.
+ :feedback_d: This would be true if it was adding up all the values in the last column, the one at index 3.
:feedback_e: This would be true if it was adding up all the values in the first row, but the row changes each time through the for loop.
What is the value of total after the following code executes?
-
+
.. code-block:: java
- int[][] matrix = { {4, 5, 6, 7}, {0, 1, 2, 3}, {3, 2, 1, 0}, {8, 9, 1, 2}};
-
+ int[][] matrix = { {4, 5, 6, 7}, {0, 1, 2, 3}, {3, 2, 1, 0}, {8, 9, 1, 2}};
+
int total = 0;
- for (int row = 0; row < len; row++)
+ for (int row = 0; row < matrix.length; row++)
{
total = total + matrix[row][1];
}
@@ -69,21 +69,21 @@ Click the |start| button when you are ready to begin the exam, but only then as
:answer_d: [16, 4, 1, 9, 3, 17, 2]
:answer_e: [2, 16, 4, 1, 9, 3, 17]
:correct: d
- :feedback_a: This would be true if it moved all of the values from the front to the back. But does it?
+ :feedback_a: This would be true if it moved all of the values from the front to the back. But does it?
:feedback_b: This would be true if the code reversed the list. But does it? Remember that remove(0) removes the first item in the list and returns it. The add method adds the item to the end of the list.
:feedback_c: This would be true if only the value 2 was moved to the end of the list. Is that what this code does?
- :feedback_d: This code moves the first item to the end of the list 4 times. So it moves the 9, 3, 17, and 2.
+ :feedback_d: This code moves the first item to the end of the list 4 times. So it moves the 9, 3, 17, and 2.
:feedback_e: This would be true if the call was mystery(3) instead of mystery(4). Then it would move the first 3 values in the list to the end of the list.
Assume that list has been initialized with the following Integer objects: [9, 3, 17, 2, 16, 4, 1]. Which of the following shows the values in list after a call of mystery(4)?
-
+
.. code-block:: java
-
+
private List list=0 - public static void mystery (int x) { - System.out.print(x % 10); + public static void mystery (int x) + { + System.out.print(x % 10); - if ((x / 10) != 0) { - mystery(x / 10); - } - System.out.print(x % 10); - } + if ((x / 10) != 0) + { + mystery(x / 10); + } + System.out.print(x % 10); + } .. mchoice:: pe3_15 :answer_a: public class Room extends Classroom implements Building { … } @@ -417,64 +430,66 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: public class Classroom extends Building, Room { … } :answer_e: public class Room extends Classroom, Building { … } :correct: b - :feedback_a: Is a Classroom a type of Building? Don't use extends unless an object of the child class can be substituted for a object of the parent class. + :feedback_a: Is a Classroom a type of Building? Don't use extends unless an object of the child class can be substituted for a object of the parent class. :feedback_b: If a classroom is a room, then Classroom should extend Room (inherit from it). If a Building has rooms it should have a field that holds them. Since a Building can have more than one Room we can use an array to hold the rooms. - :feedback_c: Is a Room a type of Building? Don't use extends unless the child is the same type of thing as the parent. - :feedback_d: You can't extend two classes in Java so this can't be right. + :feedback_c: Is a Room a type of Building? Don't use extends unless the child is the same type of thing as the parent. + :feedback_d: You can't extend two classes in Java so this can't be right. :feedback_e: You can't extend two classes in Java so this can't be right. A classroom is a room and a building has many rooms. If the three classes Room, Classroom, and Building create objects that have the same relationship which of the following is the most appropriate set of declarations? - + .. mchoice:: pe3_16 - :answer_a: Whenever the first element in a is equal to val - :answer_b: Whenever a contains any element which equals val. - :answer_c: Whenever more than 1 element in a is equal to val. - :answer_d: Whenever exactly 1 element in a is equal to val. + :answer_a: Whenever the first element in a is equal to val + :answer_b: Whenever a contains any element which equals val. + :answer_c: Whenever more than 1 element in a is equal to val. + :answer_d: Whenever exactly 1 element in a is equal to val. :answer_e: Whenever the last element in a is equal to val. :correct: c :feedback_a: What is count for? :feedback_b: It only sets temp to true when count is greater than 1. - :feedback_c: This increments count once for each value in a that is equal to val. It returns true when count is greater than 1. + :feedback_c: This increments count once for each value in a that is equal to val. It returns true when count is greater than 1. :feedback_d: This would be true if it was temp = count == 1. - :feedback_e: This could be one line of code return (a[a.length-1] == val). + :feedback_e: This could be one line of code return (a[a.length-1] == val). Given the following code which of the answers best describes the conditions needed for temp to be true when it is returned? - + .. code-block:: java - - boolean temp = false; + + boolean temp = false; int count = 0; for ( int testVal : a) - { - if ( testVal == val ) count++; - } + { + if ( testVal == val ) + count++; + } temp = count > 1; - return temp; + return temp; + - .. mchoice:: pe3_17 :answer_a: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 5 1 5 2 - :answer_b: 1 2 2 4 3 6 4 8 - :answer_c: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 + :answer_b: 1 2 2 4 3 6 4 8 + :answer_c: 1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2 :answer_d: 5 10 15 4 8 12 3 6 9 2 4 6 1 2 3 :answer_e: 1 2 2 4 3 6 4 8 5 10 :correct: e - :feedback_a: This would be true if line 3 was: System.out.print(j + " " + k + " "); + :feedback_a: This would be true if line 3 was: System.out.print(j + " " + k + " "); :feedback_b: This would be true if line 1 was: for (int j = 1; j < 5; j++). - :feedback_c: This would be true if line 1 was: for (int j = 1; j < 5; j++) and if line 3 was: System.out.print(j + " " + k + " "); + :feedback_c: This would be true if line 1 was: for (int j = 1; j < 5; j++) and if line 3 was: System.out.print(j + " " + k + " "); :feedback_d: This would be true if line 1 was: for (int j = 5; j >=1; j--) and line 2 was: for (int k = 1; k <= 3; k++). - :feedback_e: This prints j * k and for each value of j from 1 to 5, k changes from 1 to 2. So when j is 1 it will print 1 2. When j is 2 it will print 2 4. When j is 3 it will print 3 6. When j is 4 it will print 4 8. When j is 5 it will print 5 10. + :feedback_e: This prints j * k and for each value of j from 1 to 5, k changes from 1 to 2. So when j is 1 it will print 1 2. When j is 2 it will print 2 4. When j is 3 it will print 3 6. When j is 4 it will print 4 8. When j is 5 it will print 5 10. What is the output from the following code segment? - + .. code-block:: java - - for (int j = 1; j <=5; j++) { - for (int k = 1; k < 3; k++) - System.out.print(j * k + " "); - } - + for (int j = 1; j <=5; j++) + { + for (int k = 1; k < 3; k++) + System.out.print(j * k + " "); + } + + .. mchoice:: pe3_18 :answer_a: method1 and method3 :answer_b: method1 only @@ -483,47 +498,86 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: all of them :correct: a :feedback_a: The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. - :feedback_b: Another will work as well. + :feedback_b: Another will work as well. :feedback_c: This one won't work. The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. :feedback_d: While method3 will work, method2 won't. The problem with method2 is that if num1==num2 the first if will execute, but so will the second if and result will be set to 1. :feedback_e: Two will work, but one will not. Consider the following methods. Which of method1, method2, and method3 would give the same result as sample? - + .. code-block:: java - - public void sample(int num1, int num2) { + + public void sample(int num1, int num2) + { int result = 99; - if (num1==num2) {result = 0;} - else if (num1>num2){result = 1;} - else {result = -1;} + if (num1==num2) + { + result = 0; + } + else if (num1>num2) + { + result = 1; + } + else { + result = -1; + } System.out.println(result); } - - public void method1(int num1, int num2) { + + public void method1(int num1, int num2) + { int result=99; - if (num1 == num2) {result = 0;} - else { - if(num1 > num2) {result = 1;} - else {result = -1;} - } - System.out.println(result); + if (num1 == num2) + { + result = 0; + } + else { + if(num1 > num2) + { + result = 1; + } + else + { + result = -1; + } + } + System.out.println(result); + } + + public void method2(int num1, int num2) + { + int result = 99; + if (num1 == num2) + { + result = 0; + } + if (num1 >= num2) + { + result = 1; + } + else + { + result = -1; + } + System.out.println(result); } - public void method2(int num1, int num2) { - int result = 99; - if (num1 == num2) {result = 0;} - if (num1 >= num2) {result = 1;} - else {result = -1;} + public void method3(int num1, int num2) + { + int result = 99 ; + if (num1 == num2) + { + result = 0; + } + if (num1 > num2) + { + result = 1; + } + if (num1 < num2) + { + result = -1; + } System.out.println(result); - } - - public void method3(int num1, int num2) { - int result = 99 ; - if (num1 == num2) {result = 0;} - if (num1 > num2) {result = 1;} - if (num1 < num2) {result = -1;} - System.out.println(result); } @@ -541,9 +595,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: How could it print 1 for the value of t when t is set to 13 initially? What are the first and last values output by the following code segment? - + .. code-block:: java - + int t = 13; while (t < 29) { @@ -551,9 +605,9 @@ Click the |start| button when you are ready to begin the exam, but only then as t++; } - + .. mchoice:: pe3_20 - :answer_a: I and III + :answer_a: I and III :answer_b: All are true :answer_c: I, III, and IV :answer_d: II and IV @@ -566,23 +620,15 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_e: These are both true, but one more is also true. Given the following code. - + .. code-block:: java - + String s1 = new String("hi"); String s2 = new String("hi"); String s3 = s2; - + Which of the following would return true: I. s1.equals(s2) II. s1 == s2 III. s2.equals(s3); - IV. s2 == s3; - - - - - - - - \ No newline at end of file + IV. s2 == s3; \ No newline at end of file diff --git a/_sources/TimedTests/test4.rst b/_sources/TimedTests/test4.rst old mode 100755 new mode 100644 index bfd2ee9af..58c1a9c3e --- a/_sources/TimedTests/test4.rst +++ b/_sources/TimedTests/test4.rst @@ -1,45 +1,45 @@ .. qnum:: :prefix: 13-3- :start: 1 - + .. highlight:: java :linenothreshold: 4 - + .. |start| image:: Figures/start.png :height: 24px :align: top :alt: start - + .. |next| image:: Figures/next.png :height: 24px :align: top :alt: next - + .. |prev| image:: Figures/prev.png :height: 24px :align: top :alt: previous - + .. |pause| image:: Figures/pause.png :height: 24px :align: top :alt: pause - + .. |finish| image:: Figures/finishExam.png :height: 24px :align: top :alt: finish exam - -Practice Exam 3 for the AP CS A Exam + +Practice Exam 3 for the AP CSA Exam ------------------------------------- -The following 20 questions are similar to what you might see on the AP CS A exam. Please answer each to the best of your ability. +The following 20 questions are similar to what you might see on the AP CSA exam. Please answer each to the best of your ability. Click the |start| button when you are ready to begin the exam, but only then as you can only take the exam once. Click on the |next| button to go to the next question. Click on the |prev| button to go to the previous question. Use the number buttons to jump to a particular question. Click the |pause| button to pause the exam (you will not be able to see the questions when the exam is paused). Click on the |finish| button after you have answered all the questions. The number correct, number wrong, and number skipped will be displayed. -.. timed:: postexam4 +.. timed:: practiceexam3 :timelimit: 45 - + .. mchoice:: pe4_1 :answer_a: All three are valid :answer_b: II only @@ -50,28 +50,32 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_a: If there is not a call to super as the first line in a child class constructor then super() is automatically added. However, this will cause a problem if the parent class does not have a no argument constructor. :feedback_b: While II is valid so is another choice. :feedback_c: While III is valid so is another choice. - :feedback_d: Since C1 has constructors that take just an int and just a String both of these are valid. - :feedback_e: C2 constructors can call C1 constructors using the super keyword. In fact this call is automatically added to C2 constructors as the first line in any C2 constructor if it isn't there. + :feedback_d: Since C1 has constructors that take just an int and just a String both of these are valid. + :feedback_e: C2 constructors can call C1 constructors using the super keyword. In fact this call is automatically added to C2 constructors as the first line in any C2 constructor if it isn't there. Consider the following partial class definitions. Which of the constructors shown below (I, II, and III) are valid for C2? - + .. code-block:: java - public class C1 { + public class C1 + { private int num; private String name; - public C1(int theNum) { + public C1(int theNum) + { num = theNum; } - - public C1(String theName) { + + public C1(String theName) + { name = theName; } // other methods not shown } - public class C2 extends C1 { + public class C2 extends C1 + { // methods not shown } @@ -79,7 +83,7 @@ Click the |start| button when you are ready to begin the exam, but only then as I. public C2 () { } II. public C2 (int quan) {super (quan); } III. public C2 (String label) { super(label); } - + .. mchoice:: pe4_2 :answer_a: x != y :answer_b: x == y @@ -89,12 +93,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: If we assume that x is not equal to y then the expression is (false && true) || (true && false) which is false. :feedback_b: If we assume that x == y is the same than using it in the full expression should return true. But, if x is equal to y you would get (true && false) || (false && true) which is false. - :feedback_c: How can this be true? Remember that && requires both expressions to be true in order to return true. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. - :feedback_d: This can be simplified to (A && !A) || (B && !B) which is (false || false) which is false. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. + :feedback_c: How can this be true? Remember that && requires both expressions to be true in order to return true. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. + :feedback_d: This can be simplified to (A && !A) || (B && !B) which is (false || false) which is false. You can think of (x==y && !(x==y)) as A && !A which is always false. You can think of ( x!=y && !(x!=y) as B && !B which is always false. :feedback_e: Since this expression is only about equality how could this be true? The Boolean expression (x==y && !(x==y)) || ( x!=y && !(x!=y)) can be simplified to which of the following? - + .. mchoice:: pe4_3 :answer_a: if (a[savedIndex] > a[j]) { j = savedIndex; } :answer_b: if (a[j] > a[savedIndex]) { savedIndex = j;} @@ -102,35 +106,38 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: if (a[j] > a[savedIndex]) { j = savedIndex;} :answer_e: if (a[j] == a[savedIndex]) { savedIndex = j; } :correct: b - :feedback_a: Should j be set to the savedIndex? + :feedback_a: Should j be set to the savedIndex? :feedback_b: This is a selection sort that is starting at end of the array and finding the largest value in the rest of the array and swapping it with the current index. :feedback_c: This would be correct if this was starting at index 0 and finding the smallest item in the rest of the array, but this starts at the end of the array instead and finds the largest value in the rest of the array. - :feedback_d: Should j be set to the savedIndex? + :feedback_d: Should j be set to the savedIndex? :feedback_e: Why would you want to change the savedIndex if the values are the same? Which of the following could be used to replace the missing code so that the method sort will sort the array a in ascending order? - + .. code-block:: java - public static void sort(int[] a) { + public static void sort(int[] a) + { int maxCompare = a.length - 1; int savedIndex = 0; int numSteps = 0; int temp = 0; - - for (int i = maxCompare; i > 0; i--) { + + for (int i = maxCompare; i > 0; i--) + { savedIndex = i; - - for (int j = i - 1; j >= 0; j--) { + + for (int j = i - 1; j >= 0; j--) + { /* missing code */ } - + temp = a[i]; a[i] = a[savedIndex]; a[savedIndex] = temp; } } - + .. mchoice:: pe4_5 :answer_a: { {4, -5, 6},{-1, -2, 3}} :answer_b: { {4, 5, 6},{1, 2, 3}} @@ -140,24 +147,24 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: e :feedback_a: How did the values in row1 change to those in row2 and vice versa? Why didn't any value change to the absolute value? :feedback_b: How did the values in row1 change to those in row2 and vice versa? - :feedback_c: This would be true if all the matrix values were changed to their absolute value. But, this only happens when the row and column index are the same. - :feedback_d: This would be true if none of the values in the matrix were changed. But, this will change the value to the absolute value when the row and column index are the same. + :feedback_c: This would be true if all the matrix values were changed to their absolute value. But, this only happens when the row and column index are the same. + :feedback_d: This would be true if none of the values in the matrix were changed. But, this will change the value to the absolute value when the row and column index are the same. :feedback_e: This only changes the value in the matrix if the row and column index are the same. So this changes the values at (0,0) and (1,1). Consider the following declarations. If matrix is initialized to be: { {-1, -2, 3},{4, -5, 6}}. What will the values in matrix be after changeMatrix(matrix) is called? - + .. code-block:: java int[][] matrix = new int[2][3]; public static void changeMatrix(int[][] matrix ) { - for (int row = 0; row < matrix.length; row++) - for(int col = 0; col < matrix[row].length; col++) - if(row==col) - matrix[row][col] = Math.abs(matrix[row][col]); + for (int row = 0; row < matrix.length; row++) + for(int col = 0; col < matrix[row].length; col++) + if(row==col) + matrix[row][col] = Math.abs(matrix[row][col]); } - + .. mchoice:: pe4_6 :answer_a: a = 4 and b = 3 :answer_b: a = 7 and b = 0 @@ -165,19 +172,19 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: a = 5 and b = 2 :answer_e: a = 9 and b = 2 :correct: b - :feedback_a: This would be true if the for loop stopped when i was equal to 4. + :feedback_a: This would be true if the for loop stopped when i was equal to 4. :feedback_b: Here are the values of a and b at the end of each loop: i=1, a=3, b=4; i=2, a=6, b=3; i=3, a=4, b=3; i=4; a=7; b=0; :feedback_c: Go back and check your values each time through the loop. - :feedback_d: This would be true if the loop stopped when i was equal to 6, but it stops when i is equal to 5. + :feedback_d: This would be true if the loop stopped when i was equal to 6, but it stops when i is equal to 5. :feedback_e: Keep a table of the variables and their values each time through the loop. - + What are the values of a and b after the for loop finishes? - + .. code-block:: java int a = 5, b = 2, temp; - - for (int i=1; i<=4; i++) + + for (int i=1; i<=4; i++) { temp = a; a = i + b; @@ -192,13 +199,13 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: 27 :correct: d :feedback_a: This would be true if it was mystery(5). - :feedback_b: How can this be? The value 0 is never returned. + :feedback_b: How can this be? The value 0 is never returned. :feedback_c: Did you notice the recursive call? - :feedback_d: This is the same as 3 to the 4th power (3 * 3 * 3 * 3 = 81). + :feedback_d: This is the same as 3 to the 4th power (3 * 3 * 3 * 3 = 81). :feedback_e: This would be true if it was mystery(3). - + Condsider the following method. What value is returned from a call of mystery(4)? - + .. code-block:: java public static int mystery(int n) @@ -208,7 +215,7 @@ Click the |start| button when you are ready to begin the exam, but only then as else return 3 * mystery (n - 1); } - + .. mchoice:: pe4_8 :answer_a: {3,6,8,5,1}, {3,5,6,8,1}, {1,3,5,6,8} :answer_b: {1,3,8,5,6}, {1,3,8,5,6}, {1,3,5,8,6}, {1,3,5,6,8} @@ -216,14 +223,14 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_d: {1,3,8,5,6}, {1,3,5,8,6}, {1,3,5,6,8} :answer_e: {1,6,3,8,5}, {1,3,6,8,5}, {1,3,5,6,8} :correct: c - :feedback_a: This is almost right, but there should be 4 of these steps. + :feedback_a: This is almost right, but there should be 4 of these steps. :feedback_b: This is selection sort, not insertion. Selection will find the smallest and swap it with the first element in the array. - :feedback_c: An insertion sort will skip the first position and then loop inserting the next item into the correct place in the sorted elements to the left of the current item. + :feedback_c: An insertion sort will skip the first position and then loop inserting the next item into the correct place in the sorted elements to the left of the current item. :feedback_d: This is selection sort, not insertion and it is also an incorrect selection sort since it skips one step. - :feedback_e: This doesn't match selection, insertion, or merge sort. - + :feedback_e: This doesn't match selection, insertion, or merge sort. + Which of the following correctly shows the iterations of an ascending (from left to right) insertion sort on an array with the following elements: {6,3,8,5,1}? - + .. mchoice:: pe4_9 :answer_a: 21 :answer_b: 18 @@ -236,18 +243,18 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This would be true if the outer loop executed 4 times and the inner loop 8, but is that right? :feedback_d: This would be true if the outer loop executed 4 times, but is that right? :feedback_e: This would be true if you added the number of times the outer loop executes and the number of times the inner loop executes, but you multiply them. - + Consider the following code segment. How many times will a * be printed? - + .. code-block:: java - for(int i = 0; i < 3; i++) - { - for(int j = 1; j <= 7; j++) + for(int i = 0; i < 3; i++) + { + for(int j = 1; j <= 7; j++) System.out.println("*"); - } + } + - .. mchoice:: pe4_10 :answer_a: A :answer_b: B @@ -260,31 +267,34 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: This will only print if both num1 and num2 are less than 0. :feedback_d: This will only print if num2 is less than 0 and num1 is greater than or equal to 0. :feedback_e: The first test will fail since num1 is less than 0, the second test will fail since num2 is greater than 0, the third test will also fail since num2 is greater than 0, which leads to the else being executed. - + Consider the following method. What is the output from conditionTest(-3,2)? - + .. code-block:: java public static void conditionTest(int num1, int num2) { - if ((num1 > 0) && (num2 > 0)) + if ((num1 > 0) && (num2 > 0)) { if (num1 > num2) System.out.println("A"); else System.out.println("B"); } - else if ((num2 < 0) && (num1 < 0)) { + else if ((num2 < 0) && (num1 < 0)) + { System.out.println("C"); } - else if (num2 < 0) { + else if (num2 < 0) + { System.out.println("D"); } - else { + else + { System.out.println("E"); } } - + .. mchoice:: pe4_11 :answer_a: hi there :answer_b: HI THERE @@ -297,9 +307,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Strings are immutable in Java which means they never change. Any method that looks like it changes a string returns a new string object. Since s1 was never changed to refer to a different string it stays the same. :feedback_d: This would be true if we asked what the value of s4 was. :feedback_e: How could this have happened? - + What is value of s1 after the code below executes? - + .. code-block:: java String s1 = "Hi There"; @@ -310,7 +320,7 @@ Click the |start| button when you are ready to begin the exam, but only then as s3 = s3.toLowerCase(); s4 = null; - + .. mchoice:: pe4_12 :answer_a: mp :answer_b: mpu @@ -323,9 +333,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: A substring of (0,3) will have 3 characters in it (index 0, index 1, and index 2). :feedback_d: Remember that the first character in a string object is at index 0. :feedback_e: A substring of (0,3) will have 3 characters in it (index 0, index 1, and index 2). - + What is the output from the following code? - + .. code-block:: java String s = "Computer Science is fun!"; @@ -334,7 +344,7 @@ Click the |start| button when you are ready to begin the exam, but only then as String s3 = s2.substring(0,3); System.out.println(s3); - + .. mchoice:: pe4_13 :answer_a: Book b = new Book(); :answer_b: Dictionary d = new Book(); @@ -342,52 +352,53 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: b :feedback_a: A object can always be declared to be of the type of the class that creates it. :feedback_b: The declared type must the the type of the class that creates the object or the type of any parent class. Dictionary is not a parent of the Book class. - :feedback_c: The declared type can be the actual type (the class that creates the object) or any parent of the actual type. - + :feedback_c: The declared type can be the actual type (the class that creates the object) or any parent of the actual type. + Given the following class declarations, which declaration below will result in a compiler error? - + .. code-block:: java - public class Book - { - // code for class + public class Book + { + // code for class } - - public class Dictionary extends Book - { - // code for class + + public class Dictionary extends Book + { + // code for class } - .. mchoice:: pe4_14 - :answer_a: 2 + :answer_a: 2 :answer_b: 5 :answer_c: 1 :answer_d: 4 :answer_e: 0 :correct: b :feedback_a: This would be true if the recursion stopped when you first the first non "x", but is that what happens? - :feedback_b: This returns the number of "x"'s it finds in the str. + :feedback_b: This returns the number of "x"'s it finds in the str. :feedback_c: Did you notice the recursive calls? :feedback_d: How does it miss one "x"? :feedback_e: Since the first character is "x" how can this be true? - - What will the method below return when called with mystery(“xxzxyxx”)? - + + What will the method below return when called with mystery("xxzxyxx")? + .. code-block:: java - public static int mystery(String str) + public static int mystery(String str) { - if (str.length() == 0) return 0; + if (str.length() == 0) + return 0; else { - if (str.substring(0,1).equals("x")) return 1 + - mystery(str.substring(1)); - else return mystery(str.substring(1)); + if (str.substring(0,1).equals("x")) + return 1 + mystery(str.substring(1)); + else + return mystery(str.substring(1)); } } - + .. mchoice:: pe4_15 :answer_a: The value is the first one in the array :answer_b: The value is in the middle of the array @@ -397,12 +408,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: This could take a long time, but there is an answer that takes longer. :feedback_b: This would be true if we were looking for the shortest execution of a binary search - :feedback_c: This would be the second value checked if the value at the middle is greater than the desired value. - :feedback_d: This will always take the longest when you are doing binary search. + :feedback_c: This would be the second value checked if the value at the middle is greater than the desired value. + :feedback_d: This will always take the longest when you are doing binary search. :feedback_e: This would be the second value checked if the value at the middle is less than the desired value. - - Which will cause the longest execution of a binary search looking for a value in an array of 9 integers? - + + Which will cause the longest execution of a binary search looking for a value in an array of 9 integers? + .. mchoice:: pe4_16 :answer_a: Awk Awk Awk Awk Awk :answer_b: This won’t compile @@ -411,25 +422,25 @@ Click the |start| button when you are ready to begin the exam, but only then as :answer_e: Meow Moo Woof Awk Awk :correct: e :feedback_a: This would be true if none of the children classes overrode the speak method, but many do. - :feedback_b: It is always okay to substitute a child object for a parent object. - :feedback_c: This would be true if Pig had a speak method that returned "Oink" and Bird had a speak method that returned "Tweet", but they do not. The inherited speak method will be called in Animal. - :feedback_d: This would be true if Pig had a speak method that returned "Oink", but it does not. - :feedback_e: Both Pig and Bird do not have a speak method so the one in Animal will be used. - - Given the following array declaration and the fact that Animal is the parent class for Bird, Dog, Pig, Cat, and Cow, what is output from looping through this array of animals and asking each object to speak()? - + :feedback_b: It is always okay to substitute a child object for a parent object. + :feedback_c: This would be true if Pig had a speak method that returned "Oink" and Bird had a speak method that returned "Tweet", but they do not. The inherited speak method will be called in Animal. + :feedback_d: This would be true if Pig had a speak method that returned "Oink", but it does not. + :feedback_e: Both Pig and Bird do not have a speak method so the one in Animal will be used. + + Given the following array declaration and the fact that Animal is the parent class for Bird, Dog, Pig, Cat, and Cow, what is output from looping through this array of animals and asking each object to speak()? + .. code-block:: java Animal[] a = { new Cat(), new Cow(), new Dog(), new Pig(), new Bird() } - - Animal that has a method speak() which returns "Awk". - Bird doesn’t have a speak method - Dog has a speak method that returns “Woof” + + Animal that has a method speak() which returns "Awk". + Bird doesn’t have a speak method + Dog has a speak method that returns "Woof" Pig doesn’t have a speak method - Cow has a speak method that returns “Moo” + Cow has a speak method that returns "Moo" Cat has a speak method that returns "Meow" - + .. mchoice:: pe4_17 :answer_a: 4 in base 8 :answer_b: 4 in base 16 @@ -439,12 +450,12 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: c :feedback_a: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. :feedback_b: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. - :feedback_c: 17 in base 16 is 23 in base 10. 13 in base 8 is 11 in base 10. The answer is 12 in base 10 which is 00001100 in base 2. - :feedback_d: This is 2 in base 10. Convert both numbers to decimal and then convert the answer to binary. + :feedback_c: 17 in base 16 is 23 in base 10. 13 in base 8 is 11 in base 10. The answer is 12 in base 10 which is 00001100 in base 2. + :feedback_d: This is 2 in base 10. Convert both numbers to decimal and then convert the answer to binary. :feedback_e: You can't just subtract the two numbers since they are in different bases. Convert both to decimal first. - + What is the result of 17 (in base 16) - 13 (in base 8)? - + .. mchoice:: pe4_18 :answer_a: s={3, 8}; b=4; :answer_b: s={3, 4}; b=4; @@ -457,9 +468,9 @@ Click the |start| button when you are ready to begin the exam, but only then as :feedback_c: Remember that the first index in an array is index 0. This code will double the second value in the array (the one at index 1). :feedback_d: Java passes arguments by creating a copy of the current value so the value of b won't be affected by changes to y. :feedback_e: Java passes arguments by creating a copy of the current value so the value of b won't be affected by changes to y. - + Consider the following method and code. What are the values of s and b after the following has executed? - + .. code-block:: java public static void test(int[] a, int y) @@ -468,11 +479,11 @@ Click the |start| button when you are ready to begin the exam, but only then as a[1] = a[1] * 2; y = y * 2; } - + int[] s = {3,4}; int b = 4; test(s,b); - + .. mchoice:: pe4_19 :answer_a: I only :answer_b: II only @@ -482,62 +493,57 @@ Click the |start| button when you are ready to begin the exam, but only then as :correct: d :feedback_a: This is true, but at least one other thing is true as well. :feedback_b: This is true, but at least one other thing is true as well. - :feedback_c: Selection sort always takes the same amount of time to execute. + :feedback_c: Selection sort always takes the same amount of time to execute. :feedback_d: Mergesort does use recursion (has a method that calls itself). Insertion sort does take longer to execute when the items to be sorted are in ascending order and you want them in descending order. - :feedback_e: Selection sort always takes the same amount of time to execute. - - Which of the following is (are) true? - + :feedback_e: Selection sort always takes the same amount of time to execute. + + Which of the following is (are) true? + .. code-block:: java - + I. Insertion sort takes longer when the array is sorted in ascending order and - you want it sorted in descending order. - II. Mergesort uses recursion. + you want it sorted in descending order. + II. Mergesort uses recursion. III. Selection sort takes less time to execute if the array is already sorted in the correct order. - + .. mchoice:: pe4_20 - :answer_a: The method is recursive and the first call it will compare 3 to 5 and then do mystery(3,4,5). - :answer_b: There are two calls: mystery(0, 4, 5) and mystery(3, 4, 5). - :answer_c: This would be true if it was mystery(0, 4, 7); - :answer_d: This would be true if we were looking for a number that isn't in the array. - :answer_e: At most this will take log base 2 of the size of the array plus one to determine that the desired value isn't in the array. + :answer_a: 1 + :answer_b: 2 + :answer_c: 3 + :answer_d: 4 + :answer_e: 5 + :feedback_a: No, the method is recursive and in the first call it will compare 3 to 5 and then do mystery(3,4,5). + :feedback_b: There are two calls: mystery(0, 4, 5) and mystery(3, 4, 5). + :feedback_c: This would be true if it was mystery(0, 4, 7); + :feedback_d: This would be true if we were looking for a number that isn't in the array. + :feedback_e: At most this will take log base 2 of the size of the array plus one to determine that the desired value isn't in the array. :correct: b - :feedback_a: 1 - :feedback_b: 2 - :feedback_c: 3 - :feedback_d: 4 - :feedback_e: 5 - + Given the following code, how many calls to mystery are made (including the first call) when mystery(0, 4, 5) is executed when arr = {1, 2, 3, 5, 7}? - + .. code-block:: java private int[] arr; - public int mystery(int low, int high, int num) { - + public int mystery(int low, int high, int num) + { + int mid = (low+high) / 2; - - if (low > high) { + + if (low > high) + { return -1; } - else if (arr[mid] < num) { + else if (arr[mid] < num) + { return mystery(mid +1, high, num); } - else if (arr[mid] > num) { + else if (arr[mid] > num) + { return mystery(low, mid - 1, num); } - else + else return mid; } - - - - - - - - - \ No newline at end of file diff --git a/_sources/TimedTests/toctree.rst b/_sources/TimedTests/toctree.rst index c3c4bd707..5c7e12f19 100644 --- a/_sources/TimedTests/toctree.rst +++ b/_sources/TimedTests/toctree.rst @@ -9,3 +9,4 @@ Timed Multiple-Choice Exams test3.rst test4.rst Exercises.rst + apbowla.rst diff --git a/_sources/Unit1-Getting-Started/Exercises.rst b/_sources/Unit1-Getting-Started/Exercises.rst index f6cc2e644..3495261aa 100644 --- a/_sources/Unit1-Getting-Started/Exercises.rst +++ b/_sources/Unit1-Getting-Started/Exercises.rst @@ -2,9 +2,9 @@ Multiple Choice Exercises ================================= .. qnum:: - :prefix: 1-9- + :prefix: 1-11- :start: 1 - + .. mchoice:: qve_1 @@ -14,17 +14,17 @@ Multiple Choice Exercises :answer_c: 3 :answer_d: 1 :correct: a - :feedback_a: Whenever the first number is smaller than the second, the remainder is the first number. Remember that % is the remainder and 3 goes into 2 0 times with a remainder of 2. - :feedback_b: This is the number of times that 3 goes into 2 but the % operator gives you the remainder. + :feedback_a: Whenever the first number is smaller than the second, the remainder is the first number. Remember that % is the remainder and 3 goes into 2 0 times with a remainder of 2. + :feedback_b: This is the number of times that 3 goes into 2 but the % operator gives you the remainder. :feedback_c: Try it. Remember that % gives you the remainder after you divide the first number by the second one. :feedback_d: This would be correct if it was 3 % 2 since 2 would go into 3 one time with a remainder of 1. What does the following code print? - - .. code-block:: java + + .. code-block:: java System.out.println(2 % 3); - + .. mchoice:: qve_2 :practice: T :answer_a: 3 @@ -33,16 +33,16 @@ Multiple Choice Exercises :answer_d: 1 :correct: c :feedback_a: This is the number of times that 5 goes into 19, but % is the remainder. - :feedback_b: This would only be true if the first number was evenly divisible by the second number. + :feedback_b: This would only be true if the first number was evenly divisible by the second number. :feedback_c: 5 goes into 19 3 times (15) with a remainder of 4 (19-15=4) - :feedback_d: This would be correct if it was 19 % 2, but here we are dividing by 5. + :feedback_d: This would be correct if it was 19 % 2, but here we are dividing by 5. What does the following code print? - - .. code-block:: java + + .. code-block:: java System.out.println(19 % 5); - + .. mchoice:: qve_3 :practice: T :answer_a: 0.3333333333333333 @@ -58,11 +58,11 @@ Multiple Choice Exercises :feedback_e: Integer division is allowed in Java. It gives an integer result. What does the following code print? - - .. code-block:: java + + .. code-block:: java System.out.println(1 / 3); - + .. mchoice:: qve_4 :practice: T :answer_a: 24 @@ -72,35 +72,35 @@ Multiple Choice Exercises :correct: d :feedback_a: This would be true if it was System.out.println(((2 + 3) * 5) - 1), but without the parentheses the multiplication is done first. :feedback_b: This would be true if it was System.out.println(2 + (3 * (5 - 1))), but without the parentheses the multiplication is done first and the addition and subtraction are handled from left to right. - :feedback_c: This will compile and run. Try it in DrJava. Look up operator precedence in Java. + :feedback_c: This will compile and run. Try it in DrJava. Look up operator precedence in Java. :feedback_d: The multiplication is done first (3 * 5 = 15) and then the addition (2 + 15 = 17) and finally the subtraction (17 - 1 = 16). What does the following code print? - - .. code-block:: java + + .. code-block:: java System.out.println(2 + 3 * 5 - 1); - + .. mchoice:: qve_5 :practice: T :answer_a: 9.6982 - :answer_b: 12 + :answer_b: 12 :answer_c: 10 :answer_d: 9 :correct: d - :feedback_a: This would be true if it was b = a. What does the (int) do? + :feedback_a: This would be true if it was b = a. What does the (int) do? :feedback_b: This is the initial value of b, but then b is assigned to be the result of casting the value in a to an integer. Casting to an integer from a double will truncate (throw away) the digits after the decimal. :feedback_c: Java does not round when converting from a double to an integer. :feedback_d: When a double is converted into an integer in Java, it truncates (throws away) the digits after the decimal. Given the following code segment, what is the value of b when it finishes executing? - - .. code-block:: java + + .. code-block:: java double a = 9.6982; int b = 12; b = (int) a; - + .. mchoice:: qve_new7 :practice: T :answer_a: It will print 0 @@ -110,20 +110,20 @@ Multiple Choice Exercises :correct: b :feedback_a: This would be true if it was System.out.println(0 / 5) :feedback_b: You can't divide by 0 so this cause a run-time error. - :feedback_c: You might think that this would be caught at compile time, but it isn't. - :feedback_d: This would be true if it was System.out.println(5 / 1) + :feedback_c: You might think that this would be caught at compile time, but it isn't. + :feedback_d: This would be true if it was System.out.println(5 / 1) What does the following code do when it is executed? - - .. code-block:: java + + .. code-block:: java System.out.println(5 / 0); - + .. mchoice:: qve_new9 :practice: T :answer_a: 0 - :answer_b: .3 + :answer_b: .3 :answer_c: 0.3333333333333333 :answer_d: 0.3 with an infinite number of 3's following the decimal point :correct: c @@ -133,11 +133,11 @@ Multiple Choice Exercises :feedback_d: The computer can not represent an infinite number of 3's after the decimal point. What will the following code print? - - .. code-block:: java + + .. code-block:: java System.out.println(1.0 / 3); - + .. mchoice:: qve_new10 :practice: T :answer_a: x = 3, y = 3, z = 9 @@ -146,26 +146,28 @@ Multiple Choice Exercises :answer_d: x = 4, y = 4, z = 9 :correct: b :feedback_a: This would be true if the x++ wasn't there. - :feedback_b: First x is set to 3, then y is also set to 3, and next z is set to 3 * 3 = 9. Finally x is incremented to 4. + :feedback_b: First x is set to 3, then y is also set to 3, and next z is set to 3 * 3 = 9. Finally x is incremented to 4. :feedback_c: You might think that y = x means that y takes x's value, but y is set to a copy of x's value. - :feedback_d: You might think that y = x means that if x is incremented that y will also be incremented, but y = x only sets y to a copy of x's value and doesn't keep them in sync. + :feedback_d: You might think that y = x means that if x is incremented that y will also be incremented, but y = x only sets y to a copy of x's value and doesn't keep them in sync. What are the values of x, y, and z after the following code executes? - - .. code-block:: java + + .. code-block:: java int x = 3; int y = x; int z = x * y; x++; - -.. raw:: html - - - - + +The Mark Complete button and green check mark are intentionally not included for this page because there may be many quiz-bank exercises on this page. + + + + + + diff --git a/_sources/Unit1-Getting-Started/Figures/BugsRocksFlowers.png b/_sources/Unit1-Getting-Started/Figures/BugsRocksFlowers.png deleted file mode 100644 index 4c81e7d99..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/BugsRocksFlowers.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/CreateNewGridWorld.png b/_sources/Unit1-Getting-Started/Figures/CreateNewGridWorld.png deleted file mode 100644 index d594932f9..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/CreateNewGridWorld.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/DrJavaBugRunner.png b/_sources/Unit1-Getting-Started/Figures/DrJavaBugRunner.png deleted file mode 100644 index 7435a44f2..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/DrJavaBugRunner.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/DrJavaInteractions.png b/_sources/Unit1-Getting-Started/Figures/DrJavaInteractions.png deleted file mode 100644 index 8218de505..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/DrJavaInteractions.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab.png b/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab.png deleted file mode 100644 index 9d4d7a5c3..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab2.png b/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab2.png deleted file mode 100644 index 7b6525110..000000000 Binary files a/_sources/Unit1-Getting-Started/Figures/DrJavaPicLab2.png and /dev/null differ diff --git a/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png b/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png new file mode 100644 index 000000000..911aee391 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/args2paramsFarm.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/assignment.png b/_sources/Unit1-Getting-Started/Figures/assignment.png new file mode 100644 index 000000000..539bcc38b Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/assignment.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg b/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg new file mode 100644 index 000000000..2f9566930 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/bronze-casting.jpg differ diff --git a/_sources/Unit1-Getting-Started/Figures/casting.jpg b/_sources/Unit1-Getting-Started/Figures/casting.jpg index bde186d16..8a8ba2c56 100644 Binary files a/_sources/Unit1-Getting-Started/Figures/casting.jpg and b/_sources/Unit1-Getting-Started/Figures/casting.jpg differ diff --git a/_sources/Unit1-Getting-Started/Figures/dog-free.png b/_sources/Unit1-Getting-Started/Figures/dog-free.png index c673bb4a9..f3e2bf280 100644 Binary files a/_sources/Unit1-Getting-Started/Figures/dog-free.png and b/_sources/Unit1-Getting-Started/Figures/dog-free.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/firstbug.jpg b/_sources/Unit1-Getting-Started/Figures/firstbug.jpg new file mode 100644 index 000000000..0882163df Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/firstbug.jpg differ diff --git a/_sources/Unit1-Getting-Started/Figures/function.png b/_sources/Unit1-Getting-Started/Figures/function.png new file mode 100644 index 000000000..0fed34740 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/function.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/ladder.png b/_sources/Unit1-Getting-Started/Figures/ladder.png new file mode 100644 index 000000000..37531ea45 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/ladder.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/method-parts.png b/_sources/Unit1-Getting-Started/Figures/method-parts.png new file mode 100644 index 000000000..797637cb1 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/method-parts.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/parameterMapping.png b/_sources/Unit1-Getting-Started/Figures/parameterMapping.png new file mode 100644 index 000000000..1be31e96a Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/parameterMapping.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/pongScore.png b/_sources/Unit1-Getting-Started/Figures/pongScore.png index c3ef46da0..ca98b7947 100644 Binary files a/_sources/Unit1-Getting-Started/Figures/pongScore.png and b/_sources/Unit1-Getting-Started/Figures/pongScore.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/pow.png b/_sources/Unit1-Getting-Started/Figures/pow.png new file mode 100644 index 000000000..976270eac Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/pow.png differ diff --git a/_sources/Unit1-Getting-Started/Figures/square-method.png b/_sources/Unit1-Getting-Started/Figures/square-method.png new file mode 100644 index 000000000..d06777333 Binary files /dev/null and b/_sources/Unit1-Getting-Started/Figures/square-method.png differ diff --git a/_sources/Unit1-Getting-Started/aboutcsa.rst b/_sources/Unit1-Getting-Started/aboutcsa.rst index eaed9e1b2..aac534681 100644 --- a/_sources/Unit1-Getting-Started/aboutcsa.rst +++ b/_sources/Unit1-Getting-Started/aboutcsa.rst @@ -1,82 +1,111 @@ -About the AP CS A Exam +About the AP CSA Exam ====================== - -This course will prepare you for the Advanced Placement Computer Science A Exam. This exam tests your programming skills in Java. - -The AP CS A exam is 3 hours long and has two sections — multiple choice and free-response. You will be given one hour and 30 minutes for each part. The first part has 40 multiple-choice questions, and the second part has 4 free response questions where you have to write Java code by hand. Each part is worth 50% of your grade. During the exam, you will have access to the |AP CS A Reference Sheet|. - -Starting in 2020, the AP CS A exam will cover the following units and will provide formative assessments called Personal Progress Checks for each unit in the AP portal. 20 hours of lab time is required in AP CS A courses to allow students to practice Java programming. Note that abstract classes, interfaces, and binary/hex conversion have been removed from AP CS A starting in 2020. This course is arranged to follow the AP CS A units and provides many interactive exercises in each unit. - -.. raw:: html - - -
| Unit | Title | Exam Weight | Class Days | Lab Days |
|---|---|---|---|---|
| Unit 1 | Primitive Types | -2.5–5% | 8-10 | |
| Unit 2 | Using Objects | 5–7.5% | 13-15 | |
| Unit 3 | Boolean Exprs/ifs | 15–17.5% | 11-13 | 3-5 - |
| Unit 4 | Iteration | 17.5–22.5% | 14-16 | 4-6 - |
| Unit 5 | Writing Classes | 5-7.5% | 12-14 | 3-6 | -
| Unit 6 | Array | 10–15% | 6-8 | - |
| Unit 7 | ArrayList | 2.5–7.5% | 10-12 | 3-6 | -
| Unit 8 | 2D Array | 7.5–10% | 10-12 | 4-7 - |
| Unit 9 | Inheritance | 5-10% | 14-15 | 3-6 - |
| Unit 10 | Recursion | 5–7.5% | 3-5 | - |
-
-
-The 4 free response questions allow students to write code to answer a problem and cover the following areas.
-
-
-- Question 1: Methods and Control Structures, where students call methods and work with control structures without the added complexity of data structures.
-- Question 2: Class, where students design and implement a described class.
-- Question 3: Array/ArrayList, where students complete program code that uses array or ArrayList objects.
-- Question 4: 2D Array, where students complete program code that uses 2D arrays.
-
-
-.. |AP CS A site| raw:: html
-
- AP CS A site
-
-.. |AP CS A CED| raw:: html
-
- AP CS A Course and Exam Description (CED)
-
+
+This curriculum will prepare you for the Advanced Placement Computer Science A
+Exam which tests your programming skills in Java.
+
+The AP CSA exam is 3 hours long and has two sections—multiple choice and
+free-response. You will be given one hour and 30 minutes for each part. The
+first part has 40 multiple-choice questions, and the second part has 4 free
+response questions where you have to write Java code by hand. Each part is worth
+50% of your grade. During the exam, you will have access to the |AP CSA
+Reference Sheet|.
+
+The 4 free response questions cover the following areas (from |AP CSA Free Response|):
+
+ - **Question 1**: Methods and Control Structures—You’ll be asked to write program
+ code to create objects of a class and call methods, and satisfy method
+ specifications using expressions, conditional statements, and iterative
+ statements.
+
+ - **Question 2**: Classes—You’ll be asked to write program code to define a new
+ type by creating a class and satisfy method specifications using
+ expressions, conditional statements, and iterative statements.
+
+ - **Question 3**: Array/ArrayList—You’ll be asked to write program code to satisfy
+ method specifications and create, traverse, and manipulate elements in 1D
+ array or ArrayList objects.
+
+ - **Question 4**: 2D Array—You’ll be asked to write program code to satisfy method
+ specifications and create, traverse, and manipulate elements in 2D array
+ objects.
+
+The College Board specifies the AP CSA course in the 10 units shown in the table
+below. On the College Board's AP Portal they provide formative assessments
+called Personal Progress Checks for each unit. This CSAwesome curriculum is
+organized around the AP CSA units and also provides many interactive exercises
+in each unit.
+
+The College Board also requires AP CSA courses to provide at least 20 hours of
+lab time for you to practice Java programming.
+
+.. container::
+ :name: aboutcsa-table
+
+ ======= ======================= =============== ========== ========
+ Unit Title Exam Weight Class Days Lab Days
+ ======= ======================= =============== ========== ========
+ 1 Primitive Types 2.5–5% 8-10
+ ------- ----------------------- --------------- ---------- --------
+ 2 Using Objects 5–7.5% 13-15
+ ------- ----------------------- --------------- ---------- --------
+ 3 Boolean Exprs/ifs 15–17.5% 11-13 3-5
+ ------- ----------------------- --------------- ---------- --------
+ 4 Iteration 17.5–22.5% 14-16 4-6
+ ------- ----------------------- --------------- ---------- --------
+ 5 Writing Classes 5-7.5% 12-14 3-6
+ ------- ----------------------- --------------- ---------- --------
+ 6 Array 10–15% 6-8
+ ------- ----------------------- --------------- ---------- --------
+ 7 ArrayList 2.5–7.5% 10-12 3-6
+ ------- ----------------------- --------------- ---------- --------
+ 8 2D Array 7.5–10% 10-12 4-7
+ ------- ----------------------- --------------- ---------- --------
+ 9 Inheritance 5-10% 14-15 3-6
+ ------- ----------------------- --------------- ---------- --------
+ 10 Recursion 5–7.5% 3-5
+ ======= ======================= =============== ========== ========
+
+For more information on the exam see the College Board |AP CSA site| and the
+200+ page |AP CSA CED|. The |AP CSA past FRQs| are available online. Here is an
+|FRQ resource| that categorizes the past FRQs by topic and provides links to
+their solutions (which are available online in many places). The College Board
+provides a question bank and formative assessment quizzes for each unit online
+for registered AP classes.
+
+Also check out this list of |CS Careers| that taking CSA can lead to. Learning
+to code is an increasingly important skill that has applications in many
+careers!
+
+
+.. |AP CSA site| raw:: html
+
+ AP CSA site
+
+.. |AP CSA CED| raw:: html
+
+ AP CSA Course and Exam Description (CED)
+
.. |CS Careers| raw:: html
- CS Careers
-
-.. |AP CS A Reference Sheet| raw:: html
+ CS Careers
+
+.. |AP CSA Reference Sheet| raw:: html
- AP CS A Java Quick Reference Sheet
-
-
-.. |AP CS A past FRQs| raw:: html
+ AP CSA Java Quick Reference Sheet
+
+.. |AP CSA past FRQs| raw:: html
+
+ AP CSA Past Free Response Questions
- AP CS A Past Free Response Questions
-
.. |FRQ resource| raw:: html
- FRQ resource
-
-
+ FRQ resource
+
.. |AP Audit| raw:: html
- AP Audit
-
-
-For more information on the exam see the College Board |AP CS A site| and the 200+ page |AP CS A CED|. The |AP CS A past FRQs| are available online. Here is an |FRQ resource| that categorizes the past FRQs by topic and provides links to their solutions (which are available online in many places). The College Board provides a question bank and formative assessment quizzes for each unit online for registered AP classes.
+ AP Audit
-Also check out this list of |CS Careers| that taking CS A can lead to. Learning to code is an increasingly important skill that has applications in many careers!
+.. |AP CSA Free Response| raw:: html
-.. raw:: html
-
-
\ No newline at end of file
+ AP CSA Free Response
diff --git a/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst b/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst
new file mode 100644
index 000000000..d43841a74
--- /dev/null
+++ b/_sources/Unit1-Getting-Started/calling-class-methods-2026.rst
@@ -0,0 +1,475 @@
+.. include:: ../common.rst
+
+
+|Time45|
+
+Calling Class Methods (preview 2026 curriculum)
+================================================
+
+Most of the methods we have used so far are **static methods**, which are also called **class methods**. These methods are associated with the class and include the keyword static in the method header. The main method is always static, which also means that there is only one copy of the method.
+
+Here is a template for a static method. In the **method header**, the keyword **static** is used before the **return type**. Up until now, we have used the keyword **void** as the return type for methods that do not return a value. We will now look at methods that calculate and return a value of a specific type.
+
+.. code-block:: java
+
+ // static method header
+ public static return-type method-name(parameters)
+ {
+ // method body
+ }
+
+
+
+Non-void Methods
+------------------
+
+.. index::
+ single: return value
+ single: void method
+ single: non-void method
+
+Most of the methods we have used so far have been **void methods**, which do not return a value. However, many methods act like mathematical functions that calculate and return a value given some arguments. These methods are called **non-void methods**. You can imagine a non-void method as a calculating machine that takes numbers as arguments and returns a calculated result or like a toaster that takes bread as an argument and changes it to return toast.
+
+.. figure:: Figures/function.png
+ :width: 400px
+ :align: center
+ :alt: function
+ :figclass: align-center
+
+ Figure 1: Method that takes arguments and returns a value
+
+In the later lesson, we will look at the Math library in Java, but consider a simple method that squares a number. For example, ``square(3)`` would return 9.
+
+.. figure:: Figures/square-method.png
+ :width: 400px
+ :align: center
+ :alt: Square Method
+ :figclass: align-center
+
+ Figure 2: The Square Method
+
+Here is a simple implementation of this method which takes an int number as an argument, squares that number, and returns the result. Notice that instead of ``static void``, the header includes ``static int`` to indicate that the method returns an integer value. There could be another **overloaded** version of this method that takes a double number and returns a double value; remember methods are overloaded when there are multiple methods with the same name but different signatures with a different number or types of parameters.
+
+.. code-block:: java
+
+ public static int square(int number)
+ {
+ int result = number * number;
+ return result;
+ }
+
+.. |visualization| raw:: html
+
+ visualization
+
+The **return** statement is used to return a value from the method back to the calling code. The return value must be the same type as the return type in the method header. The return statement also ends the method execution, so any code after the return statement is not executed. Let's try this below. Click on the next button to step through the code in the |visualization| below and see the variables and the return values.
+
+.. codelens:: squareviz
+ :language: java
+ :optional:
+
+ public class SquareMethod
+ {
+ public static int square(int number)
+ {
+ int result = number * number;
+ return result;
+ }
+
+ public static void main(String[] args)
+ {
+ int x = 5;
+ int y = square(x);
+ System.out.println("The square of " + x + " is " + y);
+ x = 4;
+ System.out.println("The square of " + x + " is " + square(x));
+ }
+ }
+
+When calling the ``square`` method, the return value can be stored in a variable or used as part of an expression. In the main method above, the variable ``y`` is assigned the return value of the ``square`` method. The return value can also be used directly in the print statement without storing it in a variable, for example ``System.out.println(square(4));``.
+
+.. code-block:: java
+
+ // Saving the returned value of the square method in a variable
+ int y = square(5);
+ System.out.println(y); // prints 25
+ // Printing the returned value of the square method directly
+ System.out.println(square(4)); // prints 16
+
+
+|CodingEx| **Coding Exercise**
+
+.. activecode:: squareMethod
+ :language: java
+ :autograde: unittest
+ :practice: T
+
+ Add another call to the square method in the main method that prints out the square of 6.
+ ~~~~
+ public class SquareMethod
+ {
+ public static int square(int number)
+ {
+ int result = number * number;
+ return result;
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println("5 squared is " + square(5));
+ // TO DO: Call the square method to print out the square of 6
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void containsCall()
+ {
+ boolean passed = checkCodeContains("square(6)", "square(6)");
+ assertTrue(passed);
+ }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "36";
+ boolean passed =
+ getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
+
+|Exercise| **Check your understanding**
+
+.. |visualization2| raw:: html
+
+ visualization
+
+.. mchoice:: traceMethods1
+ :random:
+ :practice: T
+ :answer_a: 11
+ :answer_b: 11.5
+ :answer_c: 92
+ :answer_d: square(3)+divide(5,2)
+ :answer_e: Nothing, it does not compile.
+ :correct: a
+ :feedback_a: Yes, the square(3) method is called first and returns 9. Then the divide(5,2) method is called and returns 2 because it does int division and leaves off the decimal part. The sum of 9 and 2 is 11.
+ :feedback_b: The divide function does integer division.
+ :feedback_c: The + here will be interpreted as addition since the methods return ints.
+ :feedback_d: The square and divide methods are called and return values that are added together.
+ :feedback_e: Try the code in an active code window.
+
+ What does the following code print out? (|visualization2|)
+
+ .. code-block:: java
+
+ public class MethodTrace
+ {
+ public static int square(int x)
+ {
+ return (x * x);
+ }
+
+ public static int divide(int x, int y)
+ {
+ return (x / y);
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(square(3) + divide(5,2));
+ }
+ }
+
+
+Common Errors with Methods
+---------------------------
+
+A common error with non-void methods is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
+
+Another common error is a mismatch in types or order for the arguments or return values. For example, if a method returns a double value, you cannot assign it to an int variable.
+
+|CodingEx| **Coding Exercise**
+
+
+.. activecode:: fixMethodCalls
+ :language: java
+ :autograde: unittest
+ :practice: T
+
+ Fix the method calls below in the main method. Make sure the type, how many, and order of the arguments match what the methods expect. Are the returned values saved in the right type of variables? Do not change the methods other than main.
+ ~~~~
+ public class MathMethods
+ {
+ /* square method returns the square of a number.
+ Do NOT change */
+ public static int square(int number)
+ {
+ return number * number;
+ }
+
+ /** divide method divides x by y to return a double result .
+ Do NOT change */
+ public static double divide(double x, double y)
+ {
+ return x / y;
+ }
+
+ public static void main(String[] args)
+ {
+ // TO DO: Fix the method calls and data types below
+ // Make sure the type, how many, and order of the
+ // arguments match what the methods expect.
+ // Make sure they are saved in the right type of variables.
+ // result1 should be 4 squared
+ // result2 should be 5 divided by 2
+ int result1 = square(4.0, 2);
+ int result2 = divide(2, 5);
+ System.out.println("4 squared is " + result1);
+ System.out.println("5 divided by 2 is " + result2);
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void containsType()
+ {
+ boolean passed = checkCodeContains("correct double type for result2", "double result2");
+ assertTrue(passed);
+ }
+ @Test
+ public void containsCall()
+ {
+ boolean passed = checkCodeContains("call to square with int 4", "square(4)");
+ assertTrue(passed);
+ }
+ @Test
+ public void containsCall2()
+ {
+ boolean passed = checkCodeContains("call to divide with the correct argument order", "divide(5,2)");
+ assertTrue(passed);
+ }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "4 squared is 16\n5 divided by 2 is 2.5";
+ boolean passed =
+ getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
+
+Methods Outside the Class
+------------------------------------
+
+In the examples above, we called the methods by using the method name. However, if we call a method from a different class, we need to include its class name. For example, if the ``square`` method is in a class called ``MathFunctions``, we would call it as ``MathFunctions.square(3)``. Class methods are typically called using the class name along with the **dot operator (.)**. When the method call occurs in the defining class, the use of the class name is optional in the call.
+
+.. image:: Figures/pow.png
+ :width: 100px
+ :align: left
+ :alt: Pow!
+
+In a later lesson, we will learn to use the methods in the ``Math`` class in Java and will need to call them with the class name ``Math``. There is a method to compute the square of a number in the ``Math`` library, but it is called ``pow`` instead of square, and it takes 2 arguments to return a number raised to the power of an exponent number. Here's a quick preview of two of the methods in the Math class:
+
+- ``Math.sqrt(double number)`` : returns the square root of a given number
+- ``Math.pow(double base, double exponent)`` : returns :math:`base^{exponent}`, the value of base, the first argument, raised to the power of exponent, the second argument.
+
+Here is an example of how to use these methods:
+
+.. code-block:: java
+
+ double x = Math.pow(3, 2); // 3^2 is 9.0
+ double y = Math.sqrt(9); // the square root of 9 is 3.0
+
+|Groupwork| Programming Challenge: Ladder on Tower
+--------------------------------------------------------
+
+.. image:: Figures/ladder.png
+ :width: 200px
+ :align: left
+ :alt: Ladder on tower
+
+The Pythagorean theorem states that the length of the hypotenuse (the side
+opposite the right angle in a right triangle) is the square root of the sum
+of the squares of the lengths of the other two sides, also called the “legs” or the width and height of the triangle. (Incidentally, the Pythagorean theorem is named for
+Pythagoras who was also the leader of the gang of Greek mathematicians who legend has it allegedly drowned their fellow mathematician for showing that
+:math:`\sqrt{2}` is irrational.) Here's the formula for this theorem:
+
+- :math:`c = \sqrt{a^{2} + b^{2}}` where :math:`a` and :math:`b` are the width and height of the triangle and :math:`c` is the length of the hypotenuse.
+
+
+One common use for the Pythagorean theorem is to calculate the length of
+ladder you will need to reach the window of your beloved, given that their
+cruel parents have locked them in a tower surrounded by a moat. The ladder
+will be the hypotenuse of a triangle whose legs are the height of the window
+of your beloved’s room in the tower and the width of the moat since you have
+to place the base of the ladder on the edge of the moat.
+
+.. mchoice:: hypotenuse-java-mc
+ :multiple_answers:
+ :random:
+ :practice: T
+
+ Which of the following are correct Java expressions to compute the hypotenuse of
+ a triangle with legs ``a`` and ``b`` given the Pythagorean Theorem :math:`c = \sqrt{a^{2} + b^{2}}` where
+ :math:`a` and :math:`b` are the lengths of the legs and :math:`c` is the
+ length of the hypotenuse?
+
+ - ``Math.sqrt(a * a + b * b)``
+
+ + ✅ ``a * a`` is a squared, likewise ``b * b``. Adding them with ``+``
+ gives us the sum which is then passed to ``Math.sqrt``.
+
+ - ``Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))``
+
+ + ✅ ``Math.pow(a, 2)`` is ``a`` squared, likewise ``Math.pow(b, 2)``.
+ Adding them with ``+`` gives us the sum which is then passed to
+ ``Math.sqrt``.
+
+ - ``Math.sqrt(a + b)``
+
+ - ❌ Close, but we need to square the lengths of the legs.
+
+ - ``a * a + b * b``
+
+ - ❌ This is the sum of the squares of the lengths of the legs which gives
+ us the square of the hypotenuse. We need a ``Math.sqrt`` to get the
+ length of the hypotenuse.
+
+
+.. activecode:: challenge-1-10-pythagorean
+ :language: java
+ :autograde: unittest
+ :practice: T
+
+ Complete the ``ladderSizeNeeded`` method below using the Pythagorean Theorem and the ``Math.sqrt`` method. Then in the main method, write a method call to test the ``ladderSizeNeeded`` method with arguments for the height of 30 and the width of 40. The method should return the length of the ladder needed to reach the window of your beloved.
+ ~~~~
+ public class LadderHelper
+ {
+ /* ladderSizeNeeded computes the hypotenuse of a right triangle
+ * given the lengths of the other two sides.
+ * @param height : the height of the window
+ * @param width : the width of the moat
+ * @return the length of the ladder needed
+ */
+ public static double ladderSizeNeeded(double height, double width)
+ {
+ double ladderSize;
+ // TODO: Calculate ladderSize using the Pythagorean theorem
+ // with the Math.sqrt and Math.pow (or just *) methods
+ // using the arguments height and width
+
+
+
+ return ladderSize;
+ }
+
+ public static void main(String[] argv)
+ {
+ double size;
+ // TODO: Call the ladderSizeNeeded method
+ // with the height of 30 and the width of 40 and save it in size.
+
+ System.out.println("Beloved, I need a " + size + " foot ladder!");
+ }
+ }
+ ====
+ import org.junit.Test;
+ import java.io.IOException;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ private void check(double height, double width)
+ {
+ double expected = Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2));
+ double got = LadderHelper.ladderSizeNeeded(height, width);
+ String label = "ladderSizeNeeded(" + height + ", " + width + ")";
+ expectExact(expected, got, label);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String expected = "Beloved, I need a 50.0 foot ladder!";
+ expect(expected, getMethodOutput("main"), "Expected output from main");
+ }
+
+ @Test
+ public void testShort() {
+ check(3, 4);
+ }
+ @Test
+ public void testTall() {
+ check(30, 40);
+ }
+
+ @Test
+ public void testRandom() {
+ check(Math.random() * 100, Math.random() * 50);
+ }
+ }
+
+
+Summary
+----------
+
+- Class methods are associated with the class (not instances of the class which we will see in later lessons).
+
+- Class methods include the keyword **static** in the header before the method name.
+
+- A **non-void method** returns a value that is the same type as the **return type** in the header.
+
+- To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression. A void method does not have a return value and is therefore not called as part of an expression.
+
+- Common errors with methods are mismatches in the order or type of arguments, return values, and forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out.
+
+- Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
+
+
+AP Practice
+-------------
+
+.. mchoice:: AP1-10-static-method
+ :practice: T
+
+ Consider the following method.
+
+ .. code-block:: java
+
+ public static double calculatePizzaBoxes(int numOfPeople, double slicesPerBox)
+ { /*implementation not shown */}
+
+ Which of the following lines of code, if located in a method in the same class as calculatePizzaBoxes, will compile without an error?
+
+ - int result = calculatePizzaBoxes(45, 9.0);
+
+ - The method calculatePizzaBoxes returns a double value that cannot be saved into an int variable.
+
+ - double result = calculatePizzaBoxes(45.0, 9.0);
+
+ - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0.
+
+ - int result = calculatePizzaBoxes(45.0, 9);
+
+ - The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. Note that the int 9 can be passed into a double parameter.
+
+ - double result = calculatePizzaBoxes(45, 9.0);
+
+ + The method calculatePizzaBoxes has an int and a double parameter and returns a double result.
+
+ - result = calculatePizzaBoxes(45, 9);
+
+ - The variable result has not been declared (with an appropriate data type).
diff --git a/_sources/Unit1-Getting-Started/csptransition.rst b/_sources/Unit1-Getting-Started/csptransition.rst
index 42622e074..3c8603276 100644
--- a/_sources/Unit1-Getting-Started/csptransition.rst
+++ b/_sources/Unit1-Getting-Started/csptransition.rst
@@ -1,30 +1,60 @@
-Transitioning from AP CSP to AP CS A
+Transitioning from AP CSP to AP CSA
====================================
-
-You may have taken the AP CSP (Computer Science Principles) course and exam which is an excellent preparation for the AP CS A course. In AP CSP or in other coding experiences, you may have used a block coding language like App Inventor, Scratch, Snap!, App Lab, etc. Block languages remove syntax errors for beginners so that they can focus on coding without worrying about typing in and spelling the commands exactly right or structuring them with the correct spacing or punctuation.
-In text-based programming like Java, here are some tips to keep in mind when you are typing in commands:
+If you have taken the AP CSP (Computer Science Principles) course and exam you
+should be well prepared for AP CSA. However, there are likely to be a few new
+things to get used to. If your CSP class used a block coding language like App
+Inventor, Scratch, Snap!, or App Lab, you learned to create program structures
+by plugging together blocks. In Java you'll find the structures are similar but
+you'll have to get used to expressing them in text.
+On the other hand, if you’ve previously used a different text-based language,
+such as Python or Javascript, while you will be used to the idea of writing
+programs in text you'll have to get used to some specific details of Java's
+syntax.
-- You must make sure you spell the commands correctly.
+Here are some tips to keep in mind when you are writing Java code, especially if
+your prior programming experience was with a block language:
-- Most text-based languages are case-sensitive which means that the commands have to match the lowercase or uppercase letters exactly too.
+- You must spell things correctly, or at least consistently. Unlike in a block
+ programming language where you know you are using the right block because you
+ dragged it from a palette, in Java names are what connect different parts of
+ your program and they need to be spelled consistently.
-- Many text-based programming languages use a semicolon (;) to end a command.
+- You must pay attention to case: names that differ only in case—one starting
+ with a lower-case letter and the other with an upper-case letter, for
+ instance—are still different.
-- Many text-based programming languages use curly brackets { } to group together commands. The curly bracket notation may be familiar to you from the AP CSP pseudocode which is very similar to Java notation.
+- Punctuation is important. In particular, most statements in Java need to end
+ with a semicolon (``;``). Leave a required semicolon out and your program
+ won't run. That’s different than this paragraph which you can still read even
+ though we forgot the period at the end of this sentence
+- Java is in the family of programming languages that use curly braces (``{}``)
+ to group together statements. The curly brace notation may be familiar to you
+ from the AP CSP pseudocode which uses them in a similar way.
+
+- You should match the indentation of your code to the structure created by your
+ curly braces. In this book you can use the "Reformat" button on coding
+ activities to make sure they match. Get in the habit of clicking it frequently
+ to keep your code tidy.
.. |open in Google Docs| raw:: html
open in Google Docs
-
-Here is a comparison of some App Inventor blocks compared to AP CSP pseudocode and Java code used in AP CS A (|open in Google Docs|).
-
+
+.. |code.org App Lab code to Java| raw:: html
+
+ code.org App Lab code to Java
+
+Here is a comparison of some App Inventor blocks compared to AP CSP pseudocode and Java code used in AP CSA (|open in Google Docs|).
+
.. raw:: html
-
+
+And here is a a comparison of |code.org App Lab code to Java|:
+
.. raw:: html
-
-
\ No newline at end of file
+
+
diff --git a/_sources/Unit1-Getting-Started/growthMindset.rst b/_sources/Unit1-Getting-Started/growthMindset.rst
index ef84fb678..1ed0074c5 100644
--- a/_sources/Unit1-Getting-Started/growthMindset.rst
+++ b/_sources/Unit1-Getting-Started/growthMindset.rst
@@ -1,43 +1,64 @@
+Growth Mindset and Pair Programming
+===================================
+
+.. index::
+ single: growth mindset
+
Growth Mindset
-===============
-
-.. index::
- single: growth mindset
-
-Learning to code can be hard at times and sometimes frustrating. However, the feeling you get when your code works is incredible! And your brain grows as you problem solve and debug your programs!
+---------------
+
+Learning to code can be hard at times and sometimes frustrating. However, the feeling you get when your code works is incredible! And your brain grows as you problem solve and debug your programs!
+
+Watch this |video| about the Growth Mindset:
-Watch this video about the Growth Mindset:
+.. |video| raw:: html
+ video
.. youtube:: WtKJrB5rOKs
- :height: 315
- :width: 560
+ :height: 400
+ :width: 600
:align: left
To practice using a growth mindset, if you find yourself saying or thinking what's in the left column, try substituting what's in the right column instead:
-
============================ =======================================
Instead of: Try Thinking/Saying:
============================ =======================================
-I’m not good at this. I can learn to do this.
+I’m not good at this. I can learn to do this.
---------------------------- ---------------------------------------
-I’m awesome at this. I’m on the right track.
+I’m awesome at this. I’m on the right track.
---------------------------- ---------------------------------------
-I give up. I’ll use a different learning strategy.
+I give up. I’ll use a different learning strategy.
---------------------------- ---------------------------------------
-This is too hard. This may take some time and effort.
+This is too hard. This may take some time and effort.
---------------------------- ---------------------------------------
I can’t make this any better I can improve it!
---------------------------- ---------------------------------------
I just can’t do programming. I’m going to train my brain to do this.
---------------------------- ---------------------------------------
-Plan A didn’t work. Let's try something else.
+Plan A didn’t work. Let's try something else.
---------------------------- ---------------------------------------
-It’s good enough. How can I improve this?
+It’s good enough. How can I improve this?
============================ =======================================
-.. raw:: html
-
-
+.. index::
+ single: pair programming
+
+Pair Programming
+-----------------
+
+In this curriculum, you are encouraged to work together in pairs to complete the programming challenges. **Pair programming** is a successful software development technique where two programmers work together at one computer. One, the driver, types in code while the other, the navigator, gives ideas and feedback. The two coders switch roles frequently. You can also try buddy programming where each person uses their own computer but helps each other while coding. The advantages of pair programming are that two heads are better than one, and pairs usually produce better code with less roadblocks. As future software developers, it's also important to learn to work in teams.
+
+Watch this |video2| about pair programming:
+
+.. |video2| raw:: html
+
+ video
+
+.. youtube:: q7d_JtyCq1A
+ :height: 400
+ :width: 600
+ :align: left
+
diff --git a/_sources/Unit1-Getting-Started/javaIDEs.rst b/_sources/Unit1-Getting-Started/javaIDEs.rst
index f1e4d635f..700b5bd13 100644
--- a/_sources/Unit1-Getting-Started/javaIDEs.rst
+++ b/_sources/Unit1-Getting-Started/javaIDEs.rst
@@ -1,35 +1,66 @@
Java Development Environments
====================================
-
-.. index::
- single: IDE
- single: Integrated Development Environment
- single: DrJava
- single: compiler
- single: repl.it
+
+.. index::
+ single: IDE
+ single: Integrated Development Environment
+ single: DrJava
+ single: compiler
+ single: replit
single: Eclipse
single: BlueJ
single: Netbeans
-
-The tool that we use to compile a Java source file into a Java class file is called a **compiler**. Most programmers use an **Integrated Development Environment** (IDE) that has the compiler built in and helps you write, compile, run, and debug programs.
+ single: VSCode
+ single: Github
+ single: JuiceMind
+ single: jGRASP
+ single: IntelliJ
+ single: PickCode
-You can learn Java by just using the interactive coding panels called **Active Code** in this e-book. If you are logged in, the Active Code will remember your changes and even show you a history of your changes to the code if you click on Load History.
+The tool that we use to compile a Java source file into a Java class file is called a **compiler**. Most programmers use an **Integrated Development Environment** (IDE) that has the compiler built in and helps you write, compile, run, and debug programs.
-However, it's a good idea to also try a Java IDE to build code outside of this e-book, especially to try coding with user input which Active Code cannot do. There are many Java IDEs available. Here are some of most popular ones used by AP CS A teachers:
+You can learn Java by just using the interactive coding panels called **Active Code** in this e-book. If you are logged in, the Active Code will remember your changes and even show you a history of your changes to the code if you click on Load History.
-repl.it
--------
+However, it's a good idea to also try a Java IDE to build code outside of this e-book, especially to try coding with user input which Active Code cannot do. There are many Java IDEs available. Here are some of most popular ones used by AP CSA teachers:
+
+Cloud IDEs
+--------------------------------------
+
+There are a lot of online cloud IDEs where you can code online in many programming languages. Most are free to start, but offer different features for a price. These are great options if you are using a Chromebook or you cannot install software on your computer or you want an easy no-installation option. Some of the Active Code samples in this e-book also include a link to online IDEs. These projects can be copied to make your own copy.
+
+Here are some popular online IDEs:
+
+- Replit (https://replit.com/) an online IDE which recently switched to only allowing 3 projects at a time for free. Be aware that Replit has turned on its AI feature for code completion for all accounts (https://replit.com/ai). Each user can turn the AI on and off at the bottom of the code window, and use an AI chat window to ask questions of the AI.
+
+- JuiceMind (https://juicemind.com/) is an online IDE that offers many free and paid features for teachers to set up classrooms like Coding Rooms. It has a built-in version of CSAwesome.
+
+- PickCode (https://pickcode.io/) is another online IDE that offers many free and paid features for setting up classrooms.
+
+
+
+Github Classroom and Codespaces
+-----------------------------------
+
+Github provides many free opportunities for students and teachers (https://docs.github.com/en/education/quickstart).
+Github Classroom (https://classroom.github.com/) allows teachers to set up a classroom based on github repositories.
+Github and git are widely used in the computer industry, so learning to use it is great experience for students.
+Github now has a cloud IDE called Codespaces (https://github.com/features/codespaces) which you can use for 60 hours a month for free or completely free if you join as a school or get approved as a teacher or student.
+In Codespaces, you can start from a blank template or a repo, open a .java file in the VSCode editor, follow prompts to install the Extension Pack for Java, click on the Run and Debug (play button), follow the prompts to install the Java debugger, and see the output of your code in the terminal.
+You can also use Copilot (https://github.com/features/copilot), which is a coding AI based on GPT, for free if you are approved for educational use.
-Repl.it (https://repl.it/) is a great online development environment that we would recommend using during this course. You can login with a Google account or make an account and create new projects (click the + new repl button and type in Java) and all of your code will be kept online in your account. Repl is a great option if you are using a Chromebook or you cannot install software on your computer or you want an easy no-installation option. Repl.it also has a free K12 public school plan (https://repl.it/account/checkout/k12_per_seat) where public school teachers can apply to get a repl.it online classroom.
+Students will need to sign up for a free Github account (https://github.com/signup) if they don't already have one in order to use Codespaces.
-Some of the Active Code samples in this e-book course also include a link to a repl.it project. These projects are public and as soon as you try to change the code, it will make a copy for you in your own repl.it account. If you are pair programming, there is also a multiplayer icon on the left in repl where you can share your code with another person, and you can both make changes at the same time.
+VSCode
+---------
-Online IDEs usually cannot use graphical user interfaces and just do input and output as text. However, repl.it has a new beta that does allow the use of the javax.swing graphical user interface library! You need to choose Java Swing instead of just Java to get this environment when you start a new repl project.
+VSCode (https://code.visualstudio.com) is a widely used coding editor which you can download on your local computers.
+It has many useful extensions. The code can be run in a terminal window in the editor. See https://code.visualstudio.com/docs/languages/java for Java support.
+This editor is different than Microsoft Visual Studio which is a very large IDE.
Dr. Java
--------
-DrJava (from http://DrJava.org) is a free, simple, easy to install and use development environment. One nice feature is the interactions pane at the bottom which lets you try out Java code without having to create a class first.
+DrJava (from http://DrJava.org) is a free, simple, easy to install and use development environment. One nice feature is the interactions pane at the bottom which lets you try out Java code without having to create a class first.
BlueJ
@@ -55,8 +86,5 @@ Netbeans (https://netbeans.org/) is one of the original Java IDEs. Here is a tu
Eclipse
-------
-Eclipse (https://www.eclipse.org/downloads/packages/installer) is what many professional Java programmers use. It may be a little complex for beginners. Here are some installation and configuration instructions for Eclipse for CS A Java: http://skylit.com/javamethods/faqs/Eclipse.pdf.
+Eclipse (https://www.eclipse.org/downloads/packages/installer) is what many professional Java programmers use. It may be a little complex for beginners. Here are some installation and configuration instructions for Eclipse for CSA Java: http://skylit.com/javamethods/faqs/Eclipse.pdf.
-.. raw:: html
-
-
\ No newline at end of file
diff --git a/_sources/Unit1-Getting-Started/method-signatures-2026.rst b/_sources/Unit1-Getting-Started/method-signatures-2026.rst
new file mode 100644
index 000000000..14c0ff7d8
--- /dev/null
+++ b/_sources/Unit1-Getting-Started/method-signatures-2026.rst
@@ -0,0 +1,712 @@
+.. include:: ../common.rst
+
+|Time45|
+
+Method Signatures (preview 2026 curriculum)
+=============================================
+
+
+Methods and Procedural Abstraction
+-----------------------------------
+
+.. index::
+ single: method
+ single: procedural abstraction
+
+Up until now, all of our code has been in the main method, but complex programs are made up of many methods. When faced with a large problem, we can break it down into smaller subproblems and solve each subproblem separately. Each of these subproblems can be a method.
+
+A **method** is a named block of code that performs a task when it is called. (A **block** of code is any section of code that is enclosed in curly braces like ``{ }``.) These named blocks of code go by many names in different programming languages: functions, procedures, subroutines, etc. In Java they are called methods, as in a method of doing something. In this unit, you will learn how to use methods written by other programmers. In latter units, you will learn how to write your own methods.
+
+**Procedural abstraction** allows a programmer to use a method and not worry about the details of how it exactly works (i.e. abstracting away the details). For example, we don't need to know how a car exactly works in order to drive. We know that if we hit the brakes, the car will stop; we can still use the brakes even if we don't really know how they exactly work. Similarly, we can use a method that someone else wrote without knowing exactly how it works. We just need to know the method's name to call it and what it needs to do its job.
+
+Method Calls
+--------------
+
+.. index::
+ single: method call
+ single: flow of control
+ single: tracing
+
+We divide up a program into multiple methods in order to organize the code to reduce its complexity and to avoid repetition of code. For example, the song "Old MacDonald Had a Farm" has a lot of repetition. Instead of writing the same code over and over in order to print the song, we can write methods that contain the repeated code and run them when needed. Click on all the repeated code in the song below and then we will learn how it can be replaced with methods.
+
+|Exercise| Check Your Understanding
+
+.. clickablearea:: repeatedcode-old-mcdonald
+ :question: Click on all the lines that are completely identical and repeated.
+ :iscode:
+ :feedback: Look for lines that are completely identical.
+
+ :click-incorrect:public static void main(String args[]) {:endclick:
+ :click-correct:System.out.println("Old MacDonald had a farm.");:endclick:
+ :click-correct:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("And on this farm, they had a cow.");:endclick:
+ :click-correct:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("With a moo moo here and a moo moo there");:endclick:
+ :click-incorrect:System.out.println("Here a moo, there a moo, everywhere a moo moo");:endclick:
+ :click-correct:System.out.println("Old MacDonald had a farm");:endclick:
+ :click-correct:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:}:endclick:
+
+Did you find some repeated lines? You may have noticed that the first two lines are repeated. When you see repeated code, that is a signal for you to make a new method!
+
+A **method call** is when the code "calls out" the method's name in order to run the code in the method. The method call always includes the method name and parentheses ``()`` and sometimes some data inside the parentheses if the method needs that to do its job. For example, when we write ``System.out.println("Hello World");``, we are calling the ``println()`` method to print out "Hello World".
+
+.. code-block:: java
+
+ // Method call
+ methodName();
+
+.. |visualization| raw:: html
+
+ visualization
+
+The Java |visualization| below shows how a song can be divided up into methods. Click on the next button below the code to step through the code and watch the red arrow jump to the method that is being run. Execution in Java always begins in the ``main`` method in the current class. Then, the **flow of control** skips from method to method as they are called. Notice that when a method ends, it returns to the line right after the method call. The ``main()`` method below calls the ``intro()`` method which calls the ``chorus()`` method. When you call the chorus() method, it skips to the chorus code, executes and prints out the chorus "E-I-E-I-O", and then returns back to the method that called it. Just like variable names, method names should be descriptive of what the method does. The methods can be in any order, but usually programmers put the main method at the end after all the methods that it uses are defined.
+
+.. codelens:: songvizOldMcdonald
+ :language: java
+ :optional:
+
+ public class OldMacDonaldSong
+ {
+ public static void intro()
+ {
+ System.out.println("Old MacDonald had a farm");
+ chorus();
+ }
+
+ public static void chorus()
+ {
+ System.out.println("E-I-E-I-O");
+ }
+
+ public static void main(String[] args)
+ {
+ intro();
+ System.out.println("And on that farm they had a cow.");
+ chorus();
+ System.out.println("With a moo moo here and a moo moo there");
+ System.out.println("Here a moo, there a moo, everywhere a moo moo");
+ intro();
+ }
+ }
+
+.. note::
+
+ A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
+
+Try writing your own method calls below to add another verse to the song.
+
+.. activecode:: song-add-calls
+ :language: java
+ :practice: T
+ :autograde: unittest
+
+ Scroll down to the main method below and add lines of code to the main method for the second verse of the Old MacDonald Song by calling the intro() and chorus() methods and printing out lines about a duck or another animal.
+ ~~~~
+ public class OldMacDonaldSong
+ {
+ public static void intro()
+ {
+ System.out.println("Old MacDonald had a farm");
+ chorus();
+ }
+
+ public static void chorus()
+ {
+ System.out.println("E-I-E-I-O");
+ }
+
+ public static void main(String[] args)
+ {
+ intro();
+ System.out.println("And on that farm they had a cow.");
+ chorus();
+ System.out.println("With a moo moo here and a moo moo there");
+ System.out.println("Here a moo, there a moo, everywhere a moo moo");
+
+ // TODO:
+ // 1. Call the method intro()
+
+ // 2. Print out the line "And on that farm..."
+ // with a duck or another animal
+
+ // 3. Call the method chorus
+
+ // 4. Print out the lines with the appropriate animal sounds
+
+ // 5. Call the method intro again
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ int num = countOccurences(code, "intro();");
+
+ boolean passed = num >= 3;
+
+ passed = getResults("3 or more", "" + num, "Calls to intro()", passed);
+ assertTrue(passed);
+ }
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ int num = countOccurences(code, "chorus();");
+
+ boolean passed = num >= 3;
+
+ passed = getResults("3 or more", "" + num, "Calls to chorus()", passed);
+ assertTrue(passed);
+ }
+ }
+
+|Exercise| **Check your understanding**
+
+.. mchoice:: songMethodsTrace
+ :practice: T
+ :answer_a: I like to eat eat eat.
+ :answer_b: I like to eat eat eat fruit.
+ :answer_c: I like to apples and bananas eat.
+ :answer_d: I like to eat eat eat apples and bananas!
+ :answer_e: Nothing, it does not compile.
+ :correct: d
+ :feedback_a: Try tracing through the print method and see what happens when it calls the other methods.
+ :feedback_b: There is a fruit() method but it does not print out the word fruit.
+ :feedback_c: The order things are printed out depends on the order in which they are called from the print method.
+ :feedback_d: Yes, the print method calls the eat method 3 times and then the fruit method to print this.
+ :feedback_e: Try the code in an active code window to see that it does work.
+
+ What does the following code print out?
+
+ .. code-block:: java
+
+ public class Song
+ {
+ public static void print()
+ {
+ System.out.print("I like to ");
+ eat();
+ eat();
+ eat();
+ fruit();
+ }
+
+ public static void fruit()
+ {
+ System.out.println("apples and bananas!");
+ }
+
+ public static void eat()
+ {
+ System.out.print("eat ");
+ }
+
+ public static void main(String[] args)
+ {
+ print();
+ }
+ }
+
+.. |visualization2| raw:: html
+
+ visualization
+
+Try this |visualization2| to see this code in action. Figuring out what the code does is called **tracing** through the code. You can do this by hand or use a tool like the one above to help you see what happens when the code runs.
+
+Methods Signature, Parameters, Arguments
+------------------------------------------
+
+.. index::
+ single: method signature
+ single: parameter
+ single: argument
+ single: return type
+ single: parameter list
+
+When using methods in a library or API, we can look up the **method signature** (or **method header**) in its documentation. A **method header** is the first line of a method that includes the method name, the return type, and the parameter list of parameters and their data types. The **return type** is the type of value that the method returns; in this lesson, we'll just look at **void** return types which means the method doesn't return anything. The **method signature** is the method header without the return type, just the method name and its parameter list. The **parameter list** is a list of variables and their data types that are passed to the method when it is called. The parameter list is enclosed in parentheses and separated by commas; it can be empty with no parameters although the parentheses must be present.
+
+For example, the ``PrintStream`` class documented in https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html contains the following method signatures for ``println`` that we use in ``System.out.println()``:
+
+- ``void println()`` which has an empty parameter list with no parameters
+- ``void println(String x)`` which will print out a ``String`` value
+- ``void println(int x)`` which will print out an ``int`` value
+
+We can call these methods with the appropriate arguments to print out the value we want. The **argument** is the actual value that is passed to the method when it is called. Here are the method calls that correspond to the method signatures above:
+
+- ``System.out.println();`` // prints a newline
+- ``System.out.println("Hello World");`` // prints a String
+- ``System.out.println(42);`` // prints an int
+
+Compare the method signature of ``println(String x)`` with the method call ``println("Hello World");`` below. The method signature contains the method name and the parameter type and variable. The method call contains only the method name and the argument value. The argument must be compatible with the data type of the parameter in the method signature and is saved in the parameter variable when the method is called. Many people use the terms parameter and argument interchangeably.
+
+.. figure:: Figures/method-parts.png
+ :width: 500px
+ :align: center
+ :alt: Method Signature and Method Call
+ :figclass: align-center
+
+ Figure 1: Method Signature and Method Call
+
+Let's take another look at the Old MacDonald Song and see if we can replace more repeated code with methods with parameters. Each verse of the song is similar except it is about a different animal and the sound it makes. Click on the words that are different in the lines that are repeated to discover what parameters we need to add to the methods.
+
+.. clickablearea:: different-code-old-mcdonald
+ :question: Click on the words that are different in the lines that are repeated.
+ :iscode:
+ :feedback: Look for lines that are similar except for a single word and click on that word.
+
+ :click-incorrect:public static void main(String args[]) {:endclick:
+ :click-incorrect:System.out.println("Old MacDonald had a farm.");:endclick:
+ :click-incorrect:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("And on this farm, they had a :endclick::click-correct:cow:endclick::click-incorrect:.");:endclick:
+ :click-incorrect:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("With a :endclick::click-correct:moo moo :endclick::click-incorrect:here and a :endclick::click-correct:moo moo :endclick::click-incorrect:there");:endclick:
+ :click-incorrect:System.out.println("Here a :endclick::click-correct:moo:endclick::click-incorrect:, there a :endclick::click-correct:moo:endclick::click-incorrect:, everywhere a :endclick::click-correct:moo moo:endclick::click-incorrect:");:endclick:
+ :click-incorrect:System.out.println("Old MacDonald had a farm");:endclick:
+ :click-incorrect:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("And on this farm, they had a :endclick::click-correct:duck:endclick::click-incorrect:.");:endclick:
+ :click-incorrect:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:System.out.println("With a :endclick::click-correct:quack quack :endclick::click-incorrect:here and a :endclick::click-correct:quack quack :endclick::click-incorrect:there");:endclick:
+ :click-incorrect:System.out.println("Here a :endclick::click-correct:quack:endclick::click-incorrect:, there a :endclick::click-correct:quack:endclick::click-incorrect:, everywhere a :endclick::click-correct:quack quack:endclick::click-incorrect:");:endclick:
+ :click-incorrect:System.out.println("Old MacDonald had a farm");:endclick:
+ :click-incorrect:System.out.println("E-I-E-I-O");:endclick:
+ :click-incorrect:}:endclick:
+
+Did you notice that there are lines that are identical except for the animal name and the sound that they make?
+
+We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job. A **parameter** (sometimes called a **formal parameter**) is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method. An **argument** (sometimes called an **actual parameter**) is a value that is passed into a method when the method is called and is saved in the parameter variable.
+
+We can make a method called ``verse`` that takes the animal and its sound to print out any verse! The parameter variables ``animal`` and ``sound`` will hold different values when the method is called.
+
+.. code-block:: java
+
+ /* This method prints out a verse for any given animal and sound.
+ @param animal - the name of the animal
+ @param sound - the sound the animal makes
+ */
+ public static void verse(String animal, String sound)
+ {
+ System.out.println("And on this farm, they had a " + animal);
+ chorus();
+ System.out.println("With a " + sound + " " + sound
+ + " here and a " + sound + " " + sound + " there");
+ System.out.println("Here a " + sound
+ + ", there a " + sound
+ + ", everywhere a " + sound + " " + sound);
+ }
+
+And the main method can now just consist of calls to the intro() and verse() methods. Main methods often look like an outline for the program, calling methods to do the work.
+
+.. code-block:: java
+
+ public static void main(String[] args)
+ {
+ intro();
+ verse("cow", "moo");
+ intro();
+ verse("duck", "quack");
+ intro();
+ }
+
+.. |visualizer2| raw:: html
+
+ Java visualizer
+
+Click on the next button below to step through this new version of the code in the |visualizer2| and watch how the argument are saved in the parameter variables with each call to the ``verse`` method.
+
+.. codelens:: songvizOldMcdonald2
+ :language: java
+ :optional:
+
+ public class OldMacDonaldSong
+ {
+ public static void intro()
+ {
+ System.out.println("Old MacDonald had a farm");
+ chorus();
+ }
+
+ public static void chorus()
+ {
+ System.out.println("E-I-E-I-O");
+ }
+
+ public static void verse(String animal, String sound)
+ {
+ System.out.println("And on this farm, they had a " + animal);
+ chorus();
+ System.out.println("With a " + sound + " " + sound
+ + " here and a " + sound + " " + sound + " there");
+ System.out.println("Here a " + sound
+ + ", there a " + sound
+ + ", everywhere a " + sound + " " + sound);
+ }
+
+ public static void main(String[] args)
+ {
+ intro();
+ verse("cow", "moo");
+ intro();
+ verse("duck", "quack");
+ intro();
+ }
+ }
+
+Let's try adding another verse to the song with a goose that honks.
+
+|CodingEx| **Coding Exercise**
+
+.. activecode:: OldMacDonaldSong2
+ :language: java
+ :autograde: unittest
+ :practice: T
+
+ Run the following code to see the song Old MacDonald using the verse and chorus methods. You can also see this code run in the visualizer by clicking on the Show Code Lens button below. Scroll down to the main method, and add another verse with the animal goose and the sound honk by calling the verse method with the appropriate arguments. Then call intro again. Repeat with another animal and sound of your choice.
+ ~~~~
+ public class OldMacDonaldSong
+ {
+ public static void intro()
+ {
+ System.out.println("Old MacDonald had a farm");
+ chorus();
+ }
+
+ public static void chorus()
+ {
+ System.out.println("E-I-E-I-O");
+ }
+
+ public static void verse(String animal, String sound)
+ {
+ System.out.println("And on this farm, they had a " + animal);
+ chorus();
+ System.out.println("With a " + sound + " " + sound
+ + " here and a " + sound + " " + sound + " there");
+ System.out.println("Here a " + sound
+ + ", there a " + sound
+ + ", everywhere a " + sound + " " + sound);
+ }
+
+ public static void main(String[] args)
+ {
+ intro();
+ verse("cow","moo");
+ intro();
+ verse("duck","quack");
+ intro();
+ // TODO:
+ // Call verse again with goose and honk
+ // and then call intro again
+
+
+ // Call verse again with another animal and sound
+ // and then call intro again
+
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testThree()
+ {
+ boolean passed = checkCodeContains("verse with goose and honk", "verse(\"goose\", \"honk\");");
+ assertTrue(passed);
+ }
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ int num = countOccurences(code, "intro();");
+
+ boolean passed = num >= 5;
+
+ passed = getResults("5 or more", "" + num, "Calls to intro", passed);
+ assertTrue(passed);
+ }
+ }
+
+When a method is called, the right method definition is found by checking the **method signature** or **header** at the top of the method definition to match the method name, the number of arguments, the data types for the arguments and the return type. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
+
+Here's what that looks like with the two method calls above. The arguments like "cow" and "moo" are saved into the parameter variables ``animal`` and ``sound`` with each method call.
+
+.. figure:: Figures/args2paramsFarm.png
+ :width: 500px
+ :align: center
+ :alt: Arguments to Parameters
+ :figclass: align-center
+
+ Figure 2: Matching Arguments to Parameters
+
+
+The method headers contain data types of the parameters because they are variable declarations that reserve memory for the parameter variables. However, the method calls never contain the parameter types, only the values that are passed to the method. The argument values can be variables, literals, or expressions that evaluate to the correct data type.
+
+.. code-block:: java
+
+ // Method headers contain data types for the parameters
+ public static void verse(String animal, String sound)
+ { /* Implementation not shown */
+ }
+
+ // Method calls contain only values for the parameters
+ verse("cow", "moo");
+
+
+Java uses **call by value** when it passes arguments to methods. This means that a copy of the value in the argument is saved in the parameter variable. Call by value initializes the parameters with copies of the arguments. If the parameter variable changes its value inside the method, the original value outside the method is not changed.
+
+Overloading
+-------------
+
+.. index::
+ single: overloading
+
+Methods are said to be **overloaded** when there are multiple methods with the same name but different signatures with a different number or types of parameters. For example, the ``println()`` method in the ``PrintStream`` class documented in https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html
+is overloaded with different parameter types. The method ``println()`` with no parameters prints a newline, the method ``println(String x)`` prints the given string followed by a newline, the method ``println(int x)`` prints the given int number followed by a newline, etc. The compiler determines which method to call based on the number and types of arguments passed to the method.
+
+
+
+|Groupwork| Programming Challenge: Song with Parameters
+---------------------------------------------------------
+
+.. |The Ants Go Marching| raw:: html
+
+ The Ants Go Marching
+
+Here's another song, |The Ants Go Marching|, that is very similar in its repetitive structure. The verses below have a lot of repeated words and phrases. Click on the words or phrases that are different in each verse. These will be the arguments that you will pass to the methods in your song code.
+
+.. clickablearea:: clickDifferentAntSong
+ :question: Click on the phrases that are different in each verse.
+ :iscode:
+ :feedback: Look for words that are different in verse 1, 2, and 3.
+
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:suck a thumb:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
+
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:tie a shoe:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
+
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:climb a tree:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
+
+
+.. activecode:: challenge-1-9-song
+ :language: java
+ :autograde: unittest
+ :practice: T
+
+ Write code in the main method that calls the verse method to print out all three verses for the Ants Go Marching song above.
+ ~~~~
+ public class AntsSong
+ {
+ public static void chorus(String num)
+ {
+ System.out.println("The ants go marching " + num
+ + " by " + num + " hurrah, hurrah");
+ System.out.println("The ants go marching " + num
+ + " by " + num + " hurrah, hurrah");
+ }
+
+ public static void verse(String num, String action)
+ {
+ System.out.println("The ants go marching " + num + " by " + num);
+ System.out.println("The little one stops to " + action);
+ System.out.println("And they all go marching down to the ground");
+ System.out.println("To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n");
+ }
+
+ public static void main(String args[])
+ {
+ // Call the chorus and verse methods
+ // with the correct arguments
+ // to print out all three verses above.
+
+
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void checkCodeContains1()
+ {
+ String code = getCode();
+ int actual = countOccurences(code, "chorus(");
+ String expected = "3";
+
+ boolean passed = actual >= 3;
+ getResults(
+ expected,
+ "" + actual,
+ "Checking that code contains 3 calls to chorus",
+ passed);
+ assertTrue(passed);
+ }
+ @Test
+ public void checkCodeContains2()
+ {
+ String code = getCode();
+ int actual = countOccurences(code, "verse(");
+ String expected = "3";
+
+ boolean passed = actual >= 3;
+ getResults(
+ expected,
+ "" + actual,
+ "Checking that code contains three calls to verse method",
+ passed);
+ assertTrue(passed);
+ }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+
+ String expect =
+ "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one\n"
+ + "The little one stops to suck a thumb\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two\n"
+ + "The little one stops to tie a shoe\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three\n"
+ + "The little one stops to climb a tree\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!";
+
+ boolean passed =
+ getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ }
+
+
+Summary
+---------
+
+.. dragndrop:: vocab1_9
+ :feedback: Review the summary below.
+ :match_1: named block of code to perform a task|||method
+ :match_2: where execution starts|||main method
+ :match_3: method name, return type, and parameter list|||method signature
+ :match_4: a variable declared in the header of a method|||parameter
+ :match_5: value passed into a method when it is called|||argument
+
+ Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct.
+
+- A **method** is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces.
+
+- **Procedural abstraction** allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
+
+- A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
+
+- A **parameter** is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor.
+
+- A **method signature** for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
+
+- An **argument** is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value.
+
+- **Call by value** initializes the parameters with copies of the arguments.
+
+- Methods are said to be **overloaded** when there are multiple methods with the same name but different signatures.
+
+AP Practice
+------------
+
+.. mchoice:: AP-trace-method-calls
+ :practice: T
+
+ Consider the following class definition.
+
+ .. code-block:: java
+
+ public class Cat
+ {
+ public static void sound1()
+ {
+ System.out.print("meow ");
+ }
+
+ public static void sound2()
+ {
+ System.out.print("purr ");
+ }
+
+ public static void hello()
+ {
+ sound2();
+ sound1();
+ }
+ }
+
+ Which of the following code segments, if located in a method inside the Cat class, will cause the message "purr meow purr" to be printed?
+
+ - .. code-block:: java
+
+ hello();
+
+ - This would print "purr meow "
+
+ - .. code-block:: java
+
+ hello();
+ sound2();
+
+ + Correct!
+
+ - .. code-block:: java
+
+ sound1()
+ sound2();
+ sound1();
+
+ - This would print out "meow purr meow" instead of "purr meow purr".
+
+ - .. code-block:: java
+
+ purr();
+ meow();
+ purr()
+
+ - This would cause a syntax error since those are not the names of the methods.
diff --git a/_sources/Unit1-Getting-Started/preface.rst b/_sources/Unit1-Getting-Started/preface.rst
index cf649ad7c..e0a05d497 100644
--- a/_sources/Unit1-Getting-Started/preface.rst
+++ b/_sources/Unit1-Getting-Started/preface.rst
@@ -1,34 +1,34 @@
-.. .. qnum::
- :prefix: 0-1-
- :start: 0
-
Preface
===============
-.. index::
- single: license
-
-CSAwesome is a free AP CS A curriculum that was created in 2019 by adapting the AP CS A Java Review e-book written by Dr. Barbara Ericson, while she was a senior research scientist at Georgia Tech, currently Assistant Professor of Information at University of Michigan. She published this book using a modified BSD license to encourage people to use it, change it, and modify it for their own purposes.
+.. index::
+ single: license
+
+CSAwesome is a free AP CSA curriculum that is endorsed by the College Board as an official AP CSA curriculum and PD provider. It was created in 2019 by adapting the AP CSA Java Review e-book written by Dr. Barbara Ericson, while she was a senior research scientist at Georgia Tech, currently Assistant Professor of Information at University of Michigan.
+
+Dr. Beryl Hoffman, Professor of Computer Science at Elms College, MA, created and adapted the CSAwesome curriculum to follow the College Board CSA 2019 guidelines with the support of a 2019 Google CS-ER grant and the Mobile CSP project (https://www.mobile-csp.org) to help transition students and teachers from AP CSP to AP CSA. Special thanks to Barb Ericson, Beth Simon, Colleen Lewis (for her awesome Java memory model videos), John Figliulo, Pauline Lake, Jennifer Rosato, Kim Evelti, Becky Stacey, Art Lopez, Kyle Gillette, and Peter Bowers for feedback, edits, and ideas.
-CSAwesome is an official College Board CS A curriculum and PD provider as of 2020. Dr. Beryl Hoffman, Associate Professor of Computer Science at Elms College, MA, created and adapted the CSAwesome curriculum to follow the College Board CS A 2019 guidelines with the support of a 2019 Google CS-ER grant and the Mobile CSP project (https://www.mobile-csp.org). Special thanks to Barb Ericson, Beth Simon, John Figliulo, Pauline Lake, Jennifer Rosato, Kim Evelti, Becky Stacey, Art Lopez, and Kyle Gillette for feedback, edits, and ideas. In the summer 2020, we are very grateful to CSA teacher extraordinaire Kate McDonnell who created JUnit test code suite for our Java server, and many volunteers including Pat Clark, Emma Brown, Emma Pinnell, who are helping to add junit tests to each active code to make them auto-gradable. Our hopes are that CSP teachers and students can use this interactive book to help transition from AP CSP to AP CS A.
+In the summer of 2020, CSA teacher extraordinaire Kate McDonnell from Cherry Creek Schools in CO created a JUnit test code suite for our Java servers to provide feedback to students in every active code. Many volunteers including Pat Clark, Emma Brown, Emma Pinnell, Megha Sharma, Arjun Balaji, and Anvita Gollu helped to add many junit tests to each active code to make them auto-gradable.
+
+In the summer of 2023, Peter Seibel, author, software developer, and Berkeley High School AP CSA teacher, began making valuable improvements to the CSAwesome text and Runestone platform.
.. |form| raw:: html
form
-
+
If you see errors or bugs, please report them with this |form|.
**Acknowledgements**
-We gratefully acknowledge the use of the Runestone platform and Jobe server run by Brad Miller, and the past use of the Jobe server from the University of Canterbury, New Zealand.
+We gratefully acknowledge the use of the Runestone platform and Jobe servers run by Brad Miller, and the past use of the Jobe server from the University of Canterbury, New Zealand.
Special thanks also to the following people that we have collaborated with:
* Jeff (Jochen) Rick made great contributions to the Parsons problems (mixed up code problems).
-* Philip Guo who created the Java Visualizer, which we link to. We would love to embed it in this ebook, but need someone to do that.
+* Philip Guo who created the Java Visualizer, which we use in the e-book.
* Paul Resnick at the University of Michigan for hosting us all at the summer 2016 hackathon for Runestone Interactive and for his input into the design of the instructor dashboard.
@@ -39,11 +39,11 @@ Thank you also to the National Science Foundation for supporting our ebook work
Any opinions, findings, and conclusions or recommendations expressed in this material
are those of the authors and do not necessarily reflect the views of the National Science Foundation.
-Google has supported this work through their Google RISE Awards: TFR14-03256, TFR14-00363, and TFR-16-01052. They have also supported our efforts
-to help more under-represented students succeed in their AP CS A courses and on the exam.
+Google has supported this work through their Google RISE Awards: TFR14-03256, TFR14-00363, and TFR-16-01052. They have also supported our efforts
+to help more under-represented students succeed in their AP CSA courses and on the exam.
Any opinions, findings, and conclusions or recommendations expressed in this material
-are those of the authors and do not necessarily reflect the views of the Google.
+are those of the authors and do not necessarily reflect the views of Google.
**Contributors**
@@ -69,6 +69,12 @@ Several students at Georgia Tech have helped review the eBook:
* Bhavika Devnani
* Stephanie Remy
+Several students from the University of Michigan have contributed to the eBook
+* Emma Brown - unit tests
+* Emma Pinnell - unit tests
+* Kira Woodhouse - Added Peer Instruction questions
+
+
Several students at the University of California, San Diego have been involved in creating multiple choice questions for the EBook.
* Matthew Crooks
@@ -96,24 +102,30 @@ Many others have been involved in the creation of content for the eBook (includi
* JP Fasano - found an error in one of the non-timed exams
* Srikar Yendapally - added code problems to the 2D array chapter
* Kiran Ruston - added new questions to the free response problems at the end of the ebook.
+* Arvindh Manian — formatted video interviews into the Stories unit of the ebook
+* Sanjana Duttagupta - added Peer Instruction questions from http://peerinstruction4cs.com/
**License**
.. figure:: https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png
:align: center
-
+
.. |creative commons| raw:: html
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
This work is licensed under a |creative commons|.
-Barbara Ericson `barbarer@umich.edu Java is fun and cool!
- Notice the println in line 2.
- .. raw:: html
-
+
- Java isfun
+ Java isfun
and cool!
- - Notice the space after is in the first line.
-
+ - Notice the space after is in the first line.
+
- .. raw:: html
-
+
Java is
- fun
+ fun
and cool!
- Notice that the first line is a print, not println.
-
+
- .. raw:: html
-
+
Java is fun
and cool!
-
+
+ Correct! Pay attention to which lines are print or println.
-
-
+
+
.. mchoice:: AP1-2-2
:practice: T
-
+
Consider the following code segment.
.. code-block:: java
-
+
System.out.println("Roses are red, ") // Line 1;
System.out.println("Violets are blue, ") // Line 2;
System.out.print("Unexpected '}' ") // Line 3;
@@ -541,30 +713,25 @@ AP Practice
The code segment is intended to produce the following output but may not work as intended.
.. raw:: html
-
+
Roses are red,
Violets are blue,
Unexpected '}' on line 32.
Which change, if any, can be made so that the code segment produces the intended output?
-
+
- Replacing print with println on lines 3 and 4.
-
+
- These should print on the same line without a newline in between.
-
+
- Replacing println with print on lines 1 and 2.
-
+
- These should print out with a newline in between.
-
+
- Removing the single quotes in line 3.
-
+
- The single quotes are fine in this line.
-
- - Putting the semicolon after the ) on each line.
-
- + Correct! The semicolon should go after each command but not in the comment.
+ - Putting the semicolon after the ) on each line.
-.. raw:: html
-
-
\ No newline at end of file
+ + Correct! The semicolon should go after each statement but not in the comment.
diff --git a/_sources/Unit1-Getting-Started/topic-1-3-variables.rst b/_sources/Unit1-Getting-Started/topic-1-3-variables.rst
index 773338ffb..dddb68e03 100644
--- a/_sources/Unit1-Getting-Started/topic-1-3-variables.rst
+++ b/_sources/Unit1-Getting-Started/topic-1-3-variables.rst
@@ -1,25 +1,12 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 1-3-
:start: 1
-
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+
+
+|Time90|
+
Variables and Data Types
========================
@@ -28,62 +15,74 @@ In this lesson, you will learn about variables and primitive data types.
What is a Variable?
-------------------
-.. index::
- single: variable
+.. index::
+ single: variable
-A **variable** is a name associated with a memory location in the computer. Computer memory can store a value and that value can change or vary. The following `video
fibonacci.
+ :feedback_c: Line 13 has two calls to fibonacci.
:feedback_d: There are not 3 calls to fibonacci.
How many recursive calls does the following method contain?
@@ -79,12 +87,19 @@ These problems are easier than most of those that you will usually see on the AP
public static int fibonacci(int n)
{
- if (n == 0)
- return 0;
- else if (n == 1)
- return 1;
- else return fibonacci(n-1) + fibonacci(n-2);
- }
+ if (n == 0)
+ {
+ return 0;
+ }
+ else if (n == 1)
+ {
+ return 1;
+ }
+ else
+ {
+ return fibonacci(n-1) + fibonacci(n-2);
+ }
+ }
.. mchoice:: qre_4
:practice: T
@@ -94,7 +109,7 @@ These problems are easier than most of those that you will usually see on the AP
:answer_d: 3
:correct: b
:feedback_a: Look for a call to the same method in the body of the method.
- :feedback_b: Line 6 has one call to multiplyEvens.
+ :feedback_b: Line 9 has one call to multiplyEvens.
:feedback_c: Where do you see 2 calls to multiplyEvens?
:feedback_d: Where do you see 3 calls to multiplyEvens?
@@ -105,9 +120,12 @@ These problems are easier than most of those that you will usually see on the AP
public static int multiplyEvens(int n)
{
- if (n == 1) {
- return 2;
- } else {
- return 2 * n * multiplyEvens(n - 1);
- }
+ if (n == 1)
+ {
+ return 2;
+ }
+ else
+ {
+ return 2 * n * multiplyEvens(n - 1);
+ }
}
diff --git a/_sources/Unit10-Recursion/rHardMC.rst b/_sources/Unit10-Recursion/rHardMC.rst
index 30b21b6da..a35fd8fb5 100644
--- a/_sources/Unit10-Recursion/rHardMC.rst
+++ b/_sources/Unit10-Recursion/rHardMC.rst
@@ -5,7 +5,7 @@
Hard Multiple Choice Questions
----------------------------------
-These problems are about the same or harder than those that you will typically see on the AP CS A exam.
+These problems are about the same or harder than those that you will typically see on the AP CSA exam.
.. mchoice:: qrh_1
:practice: T
@@ -52,10 +52,14 @@ You can step through the code above by clicking on the following link `Ex-11-8-1
public static int redo(int i, int j)
{
- if (i==0)
- return 0;
- else
- return redo(i/j, j)+1;
+ if (i == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ return redo(i / j, j) + 1;
+ }
}
You can step through the code above by clicking on the following link `Ex-11-8-2 mystery with the integer 1234 will print 1234 % 10. The '%' means modulo or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
+ :feedback_a: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
:feedback_b: This has a recursive call which means that the method calls itself when (x / 10) is greater than or equal to zero. Each time the method is called it prints the remainder of the passed value divided by 10 and then calls the method again with the result of the integer division of the passed number by 10 (which throws away the decimal part). After the recursion stops by (x / 10) == 0 the method will print the remainder of the passed value divided by 10 again.
- :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulo or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
- :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means modulo or remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
+ :feedback_c: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
+ :feedback_d: The first call to mystery with the integer 1234 will print 1234 % 10. The '%' means remainder. The remainder of 1234 divided by 10 is 4 so the first thing printed must be 4.
:feedback_e: When the recursive call to mystery(1) occurs (the 4th call to mystery), the division of x /10 equals .01--this becomes 0 because this is integer division and the remainder is thrown away. Therefore the current call will be completed and all of the previous calls to mystery will be completed.
Given the following method declaration, which of the following is printed as the result of the call ``mystery(1234)``?
@@ -29,13 +29,13 @@ These problems are similar to those you will see on the AP CS A exam.
//precondition: x >=0
public static void mystery (int x)
{
- System.out.print(x % 10);
+ System.out.print(x % 10);
- if ((x / 10) != 0)
- {
- mystery(x / 10);
- }
- System.out.print(x % 10);
+ if ((x / 10) != 0)
+ {
+ mystery(x / 10);
+ }
+ System.out.print(x % 10);
}
You can step through the code using the Java Visualizer by clicking on the following link: `Q-11-7-1
but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn right, go forward, turn left, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.
- ----- - import java.util.*; - import java.awt.*; - ===== - public class TurtleTest { - ===== - public static void main(String[] args) { - ===== - World world = new World(300,300); - Turtle yertle = new Turtle(world); - ===== - yertle.turnRight(); - ===== - yertle.right(); #paired - ===== - yertle.forward(); - ===== - yertle.forward() #paired - ===== - yertle.turnLeft(); - ===== - yertle.forward(50); - ===== - world.show(true); - ===== - world.show(True); #paired - ===== - } // end main - } // end class - - -A computer doesn't automatically know what we mean by a robot turtle or world. We have to write Java classes to define what we -mean. The class defines the data that every turtle object knows about itself (called **fields** or **attributes**) like where it is in the world and which way it is facing. The class also defines -what objects of the class can do (called **methods** or **behaviors**) like ``turnRight`` and move ``forward``. .. mchoice:: 2_1_type_object :answer_a: object @@ -225,73 +289,51 @@ what objects of the class can do (called **methods** or **behaviors**) like ``tu What type of thing is the position of a turtle in a world? -Classes can **inherit** attributes and methods from another class in Java, just like people can inherit money from a relative. Here is a class diagram that shows some of the attributes and methods that the class ``Turtle`` inherits from the ``SimpleTurtle`` class. +.. raw:: html -.. creately.com for figure +
+.. parsonsprob:: 2_1_Turtle_L
+ :practice: T
+ :numbered: left
+ :adaptive:
+ :noindent:
-.. figure:: Figures/turtleUMLClassDiagram.png
- :width: 400px
- :align: center
- :alt: Turtle class diagram
- :figclass: align-center
-
- Figure 2: Turtle Class Diagram
+ The following program uses a turtle to draw a sort-of sideways capital L as seen in the image, but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a habitat and turtle. Then it should ask the turtle to turn right, go forward, turn left, and then go forward 50 pixels. Next, it should ask the habitat to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.
+ -----
+ import java.util.*;
+ import java.awt.*;
+ =====
+ public class TurtleTest {
+ =====
+ public static void main(String[] args) {
+ =====
+ World habitat = new World(300,300);
+ Turtle yertle = new Turtle(habitat);
+ =====
+ yertle.turnRight();
+ =====
+ yertle.right(); #paired
+ =====
+ yertle.forward();
+ =====
+ yertle.forward() #paired
+ =====
+ yertle.turnLeft();
+ =====
+ yertle.forward(50);
+ =====
+ habitat.show(true);
+ =====
+ habitat.show(True); #paired
+ =====
+ } // end main
+ } // end class
-.. mchoice:: 2_1_type_turn
- :practice: T
- :answer_a: object
- :answer_b: class
- :answer_c: attribute
- :answer_d: method
- :correct: d
- :feedback_a: An object has data and behavior.
- :feedback_b: A class defines the data and behavior for all objects of that type.
- :feedback_c: An attribute is something the object knows about itself.
- :feedback_d: A method is something an object can do like turn.
-
- A turtle object knows how to turn by a specified number of degrees. What type of thing is turn?
-
-.. parsonsprob:: 2_1_Turtle_Turn
- :numbered: left
- :adaptive:
- :noindent:
-
- The following program uses a turtle to draw the picture shown to the left,
but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn 45 degrees, go forward 100 pixels, turn right, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.
- ----- - import java.util.*; - import java.awt.*; - ===== - public class TurtleTest { - ===== - public static void main(String[] args) { - ===== - World world = new World(300,300); - Turtle yertle = new Turtle(world); - ===== - yertle.turn(45); - ===== - yertle.turnRight(45); #paired - ===== - yertle.forward(100); - ===== - yertle.turnRight(); - ===== - yertle.forward(50); - ===== - yertle.forward(50; #paired - ===== - world.show(true); - ===== - world.show(true) #paired - ===== - } // end main - } // end class |CodingEx| **Coding Exercise** - .. activecode:: TurtleTest2 :language: java :autograde: unittest @@ -299,30 +341,34 @@ Classes can **inherit** attributes and methods from another class in Java, just In the code below, ``yertle`` goes forward and then turns left. Can you change the code to make ``yertle`` go ``forward`` twice and then ``turnRight``? ~~~~ - import java.util.*; import java.awt.*; + import java.util.*; public class TurtleTest2 { - public static void main(String[] args) - { - World world = new World(300,300); - Turtle yertle = new Turtle(world); + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); - yertle.forward(); - yertle.turnLeft(); + yertle.forward(); + yertle.turnLeft(); - world.show(true); - } + habitat.show(true); + } } + ==== import static org.junit.Assert.*; - import org.junit.*;; + + import org.junit.*; + import java.io.*; public class RunestoneTests extends CodeTestHelper { - public RunestoneTests() { + public RunestoneTests() + { super("TurtleTest2"); } @@ -334,7 +380,7 @@ Classes can **inherit** attributes and methods from another class in Java, just int count = countOccurences(code, expect); - boolean passed = getResults("2 time(s)", "" + count + " time(s)", "yertle.forward() twice"); + boolean passed = getResults("2 time(s)", "" + count + " time(s)", "yertle.forward() twice"); assertTrue(passed); } @@ -352,6 +398,9 @@ Classes can **inherit** attributes and methods from another class in Java, just } } +Creating Turtle Objects +------------------------ + When you write a class like the ``Turtle`` class, you can create many objects of that class type. In the code below, two turtle objects are created: ``yertle`` and ``myrtle``. You can name your turtle and add in a line like the following in the main method to make it move: @@ -359,7 +408,7 @@ two turtle objects are created: ``yertle`` and ``myrtle``. You can name your tu // To create or declare a new object, write: // ClassName variableName = new ClassName(arguments); - Turtle yourTurtleName = new Turtle(world); + Turtle yourTurtleName = new Turtle(habitat); yourTurtlename.forward(); |CodingEx| **Coding Exercise:** @@ -371,35 +420,39 @@ two turtle objects are created: ``yertle`` and ``myrtle``. You can name your tu Can you add another turtle object to the code below? ~~~~ - import java.util.*; import java.awt.*; + import java.util.*; public class TurtleTest3 { - public static void main(String[] args) - { - World world = new World(300,300); - Turtle yertle = new Turtle(world); - Turtle myrtle = new Turtle(world); + public static void main(String[] args) + { + World habitat = new World(300, 300); + Turtle yertle = new Turtle(habitat); + Turtle myrtle = new Turtle(habitat); - yertle.forward(); - yertle.turnLeft(); - yertle.forward(); + yertle.forward(); + yertle.turnLeft(); + yertle.forward(); - myrtle.turnRight(); - myrtle.forward(); + myrtle.turnRight(); + myrtle.forward(); - world.show(true); - } + habitat.show(true); + } } + ==== import static org.junit.Assert.*; - import org.junit.*;; + + import org.junit.*; + import java.io.*; public class RunestoneTests extends CodeTestHelper { - public RunestoneTests() { + public RunestoneTests() + { super("TurtleTest3"); } @@ -407,103 +460,30 @@ two turtle objects are created: ``yertle`` and ``myrtle``. You can name your tu public void test1() { String code = getCode(); - String expect = "new Turtle(world)"; + String expect = "new Turtle(habitat)"; int count = countOccurences(code, expect); boolean passed = count >= 3; - passed = getResults("3+ Turtles", "" + count + " Turtles", "Add a new Turtle(s)", passed); + passed = getResults("3+ Turtles", "" + count + " Turtles", "Add a new Turtle(s)", passed); assertTrue(passed); } } +Here is a class diagram that shows some of the attributes and methods in the class ``Turtle``. +.. creately.com for figure -What are Classes and Objects? ------------------------------ - -In Java, a **class** is used to define a new **abstract data type** (classify something). The class defines what objects of the class need to know (attributes or instance variables) and do (behaviors or methods). A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. - -There are many classes that are part of the Java language, but you only have to know a few of these for the AP CS A exam (``String``, ``Math``, ``System``, ``ArrayList``). - -The real power of Java is the ability to create your own classes (define your own types). You will learn how to create your own classes in Unit 5. - -.. |Greenfoot video| raw:: html - - Greenfoot video - -Here's a |Greenfoot video|, which was created using the free software Greenfoot (http://greenfoot.org), where you can see ant objects doing actions like moving and eating. Greenfoot makes it easy to create 2d simulations and games in Java. See http://www.greenfoot.org/doc/tut-2 for a tutorial if you are interested in learning more about Greenfoot. - -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.png - :width: 300px - :align: center - :figclass: align-center - - Figure 3: 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). They are all different, but they share the same attributes and behaviors that make up a cat. - -.. figure:: Figures/cats2.png - :width: 300px +.. figure:: Figures/turtleUMLClassDiagram.png + :width: 400px :align: center + :alt: Turtle class diagram :figclass: align-center - Figure 4: Pictures of cats (cat objects) - + Figure 3: Turtle Class Diagram -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 attributes (called **instance variables** 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. For example, all turtle objects will know how to move forward and turn. -|Exercise| **Check your understanding** - -.. mchoice:: q2_2_1 - :practice: T - :answer_a: 1 - :answer_b: 10 - :answer_c: 1000 - :answer_d: As many as you need - :correct: d - :feedback_a: There is one definition of a class, but the class can create as many objects as are needed. - :feedback_b: There is no limit on the number of objects you can create from a class. - :feedback_c: There is no limit on the number of objects you can create from a class. - :feedback_d: You can create as many objects as you need from one class. - - How many objects can you create from a class in Java? - -.. mchoice:: q2_2_2 - :practice: T - :answer_a: attributes - :answer_b: methods - :answer_c: class - :answer_d: object - :correct: b - :feedback_a: attributes specify the data that an object keeps track of. - :feedback_b: Methods specify the behavior of all objects of a class. - :feedback_c: While the class does specify the behavior of all objects created by that class, what part of a class specifies the behavior? - :feedback_d: The object behavior is specified by the methods in the class that created the object. - - What specifies the behavior for objects of a class in Java? - -.. mchoice:: q2_2_3 - :practice: T - :answer_a: attributes - :answer_b: methods - :answer_c: class - :answer_d: object - :correct: a - :feedback_a: attributes specify the data that an object keeps track of. - :feedback_b: Methods specify the behavior of all objects of a class. - :feedback_c: While the class does specify the data 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 attributes of the object. The attributes are defined in the class. - - What specifies the data or state for an object in Java? - - -.. shortanswer:: cats - - What are some attributes of cats? What are some behaviors of cats? (Note that attributes are nouns or adjectives describing features of cats, and behaviors are verbs). |Groupwork| Programming Challenge : Turtle Drawing @@ -520,42 +500,46 @@ Create a ``Turtle`` object below and have it draw a shape. For example, have it - ``penUp();`` - ``penDown();`` -After writing your code below, if you'd like your own copy, you can open this |repl link|, copy in your code, and save it in your own repl.it account. + .. activecode:: challenge2-1-TurtleDraw :language: java :autograde: unittest :datafile: turtleClasses.jar - import java.util.*; + Create a Turtle object and have it draw a shape, for example a small square and then a larger square (by calling the forward method multiple times). + ~~~~ import java.awt.*; + import java.util.*; public class TurtleTest { - public static void main(String[] args) - { - World world = new World(500,500); - // 1. Create a Turtle object in the world - - // 2. Have the turtle draw a small square - - // 3. Have the turtle draw a large square + public static void main(String[] args) + { + World habitat = new World(500, 500); + // 1. Create a Turtle object in the habitat - // 4. Play around! + // 2. Have the turtle draw a small square + // 3. Have the turtle draw a large square + // 4. Play around! - world.show(true); - } + habitat.show(true); + } } + ==== import static org.junit.Assert.*; - import org.junit.*;; + + import org.junit.*; + import java.io.*; public class RunestoneTests extends CodeTestHelper { - public RunestoneTests() { + public RunestoneTests() + { super("TurtleTest"); } @@ -563,13 +547,18 @@ After writing your code below, if you'd like your own copy, you can open this |r public void test1() { String code = getCode(); - String expect = "new Turtle(world)"; + String expect = "new Turtle(habitat)"; int count = countOccurences(code, expect); boolean passed = count >= 1; - passed = getResults("1+ Turtle(s)", "" + count + " Turtle(s)", "At least 1 Turtle", passed); + passed = + getResults( + "1+ Turtle(s)", + "" + count + " Turtle(s)", + "At least 1 Turtle in habitat", + passed); assertTrue(passed); } @@ -578,15 +567,20 @@ After writing your code below, if you'd like your own copy, you can open this |r { String code = getCode(); String right = ".turnRight()"; - String left = ".turnLeft()"; + String left = ".turnLeft()"; int countR = countOccurences(code, right); int countL = countOccurences(code, left); int count = countR + countL; - boolean passed = countR >= 8 || countL >= 8 || (countL >= 4 && countR >= 4); + boolean passed = countR >= 6 || countL >= 6 || (countL >= 3 && countR >= 3); - passed = getResults("8+ turns", "" + count + " turns(s)", "two squares (8 right or left turns total)", passed); + passed = + getResults( + "6+ turns", + "" + count + " turns(s)", + "two squares (6+ right or left turns total)", + passed); assertTrue(passed); } @@ -603,42 +597,58 @@ After writing your code below, if you'd like your own copy, you can open this |r boolean passed = forward >= 8 || backward >= 8 || (backward >= 4 && forward >= 4); - passed = getResults("8+ moves", "" + moves + " move(s)", "two squares (8 moves total)", passed); + passed = + getResults( + "8+ moves", "" + moves + " move(s)", "two squares (8 moves total)", passed); assertTrue(passed); } @Test - public void test4() { + public void test4() + { String[] code = getCode().split("\n"); int expect = 38; boolean passed = code.length >= expect; - passed = getResults(expect + "+ line(s)", "" + code.length + " lines(s)", "More than " + expect + " lines of code", passed); + passed = + getResults( + expect + "+ line(s)", + "" + code.length + " lines(s)", + "More than " + expect + " lines of code", + passed); assertTrue(passed); } } - Summary ------------------- - A **class** defines a new data type (a classification). It is the formal implementation, or blueprint, of the *attributes* and *behaviors* of the objects of that class. -- An **object** is a specific instance of a class with defined attributes. Objects are declared as variables of a class type. - -- An **attribute** is data the object knows about itself. For example a turtle object knows the direction it is facing. - -- A **method** is something that an object can do. For example a turtle object can go forward 100 pixels. +- An **object** is a specific **instance** of a class with defined attributes. Objects are declared as variables of a class type. -- An **abstract data type** is a definition of the attributes and methods for all objects of a type (of the same class). +- An **attribute** or **instance variable** is data the object knows about itself. For example a turtle object knows the direction it is facing or its color. -- An **instance variable** is another name for an attribute, which is data an object knows about itself such as its position. +- A **behavior** or **method** is something that an object can do. For example a turtle object can go forward 100 pixels. AP Practice ------------ +.. |video3| raw:: html + + video + +This |video3| shows another class called Belt and how it has 3 instance variables to define its attributes. Every belt object has its own copy of instance variables. + +.. youtube:: Y9vn6u3901Y + :width: 650 + :height: 415 + :align: center + :optional: + +Try these AP practice questions that will help to prepare you for the AP Classroom progress checks. .. mchoice:: AP2-1-1 :practice: T @@ -665,13 +675,13 @@ AP Practice .. mchoice:: AP2-1-2 :practice: T - :answer_a: An attribute of the myParty object is boolean. - :answer_b: An attribute of the Party class is myParty. - :answer_c: An instance of the Party class is myParty. - :answer_d: An attribute of the Party instance is myParty. - :answer_e: An instance of the Party object is numOfPeople. + :answer_a: boolean is an attribute of the myParty object. + :answer_b: myParty is an attribute of the Party class. + :answer_c: myParty is an instance of the Party class. + :answer_d: myParty is an attribute of the Party instance. + :answer_e: numOfPeople is an instance of the Party object. :correct: c - :feedback_a: An attribute of myParty is numOfPeople. + :feedback_a: boolean is the type of an attribute, but not an attribute. :feedback_b: myParty is an instance of the Party class. :feedback_c: myParty is an object that is an instance of the Party class. :feedback_d: An attribute of the Party class is numOfPeople. @@ -1434,9 +1444,9 @@ AP Practice import java.awt.geom.*; import java.io.ByteArrayOutputStream; - // import javax.xml.bind.DatatypeConverter; + // import javax.xml.bind.DatatypeConverter; // Using java.util.Base64 instead of javax.xml.bind - import java.util.Base64; + import java.util.Base64; import java.util.Scanner; /** @@ -1800,10 +1810,10 @@ AP Practice ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(this.bufferedImage, "png", output); String result = - // DatatypeConverter.printBase64Binary(output.toByteArray()); + // DatatypeConverter.printBase64Binary(output.toByteArray()); // using java.util.Base64 instead of java.xml.bind.DataTypeConverter - Base64.getEncoder().encodeToString(output.toByteArray()); - System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); + Base64.getEncoder().encodeToString(output.toByteArray()); + System.out.println("<img src=\'data:image/" + this.extension + ";base64," + result + "\'/>"); } catch (IOException e) { System.out.println("Errors occured in image conversion"); } @@ -2319,6 +2329,15 @@ AP Practice */ public void setPicture(Picture pict) { this.picture = pict; } + /** + * Method to set the speed of animation by setting the delay to between 0-100. + * 50 is the default. We pass this to the World's setSpeed method. + * @param d + */ + public void setSpeed(int d) { + ((World)modelDisplay).setSpeed(d); + } + /** * Method to get the model display for this simple turtle * @return the model display if there is one else null @@ -2858,7 +2877,7 @@ AP Practice { // let the parent constructor handle it super(p); - } + } } // this is the end of class Turtle, put all new methods before this /** @@ -2899,148 +2918,148 @@ AP Practice public abstract class Giffer { - // Generate gif from an array of filenames - // Make the gif loopable if loop is true - // Set the delay for each frame according to the delay (ms) - // Use the name given in String output for output file - public static void generateFromFiles(String[] filenames, String output, int delay, boolean loop) - throws IIOException, IOException - { - int length = filenames.length; - BufferedImage[] img_list = new BufferedImage[length]; - - for (int i = 0; i < length; i++) - { - BufferedImage img = ImageIO.read(new File(filenames[i])); - img_list[i] = img; - } - - generateFromBI(img_list, output, delay, loop); - } - - // Generate gif from BufferedImage array - // Make the gif loopable if loop is true - // Set the delay for each frame according to the delay, 100 = 1s - // Use the name given in String output for output file - public static void generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) - throws IIOException, IOException - { - int maxWidth = 0; - int maxHeight = 0; - ImageWriter gifWriter = getWriter(); - ImageOutputStream ios = getImageOutputStream(output); - IIOMetadata metadata = getMetadata(gifWriter, delay, loop); - - //Get bigger Width and Height - for (BufferedImage img: images) - { - if(img.getHeight() > maxHeight){ - maxHeight = img.getHeight(); - } - if(img.getWidth() > maxWidth){ - maxWidth = img.getWidth(); - } - } - - gifWriter.setOutput(ios); - gifWriter.prepareWriteSequence(null); - for (BufferedImage img: images) - { - BufferedImage dimg = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB); - Image tmp = img.getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT); - Graphics2D g2d = dimg.createGraphics(); - int centerWidth = (maxWidth / 2) - (img.getWidth()/2) ; - g2d.drawImage(tmp, centerWidth, 0, null); - g2d.dispose(); - - IIOImage temp = new IIOImage(dimg, null, metadata); - gifWriter.writeToSequence(temp, null); - } - - gifWriter.endWriteSequence(); - } - - // Retrieve gif writer - private static ImageWriter getWriter() throws IIOException - { - Iterator
+
+.. parsonsprob:: 2_1_Turtle_Turn
+ :numbered: left
+ :adaptive:
+ :noindent:
+
+ The following program uses a turtle to draw the picture shown to the left, but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn 45 degrees, go forward 100 pixels, turn right, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.
+ -----
+ import java.util.*;
+ import java.awt.*;
+ =====
+ public class TurtleTest {
+ =====
+ public static void main(String[] args) {
+ =====
+ World world = new World(300,300);
+ Turtle yertle = new Turtle(world);
+ =====
+ yertle.turn(45);
+ =====
+ yertle.turnRight(45); #paired
+ =====
+ yertle.forward(100);
+ =====
+ yertle.turnRight();
+ =====
+ yertle.forward(50);
+ =====
+ yertle.forward(50; #paired
+ =====
+ world.show(true);
+ =====
+ world.show(true) #paired
+ =====
+ } // end main
+ } // end class
+
+Here is the Turtle class diagram again that shows some of the variables and methods inherited from the SimpleTurtle class in the class Turtle that are written for you.
.. figure:: Figures/turtleUMLClassDiagram.png
:width: 400px
@@ -83,25 +106,25 @@ Here is the Turtle class diagram again that shows some of the variables and meth
:figclass: align-center
Figure 1: Turtle Class Diagram
-
+
.. |Color| raw:: html
Color
-
+
.. |javadoc (documentation) file| raw:: html
- javadoc (documentation) file
+ javadoc (documentation) file
-Try some of the methods above in the turtle code below. You can see all the methods that are inherited in Turtle in this |javadoc (documentation) file|.
+Try some of the methods above in the turtle code below. You can see all the methods that are inherited in Turtle in this |javadoc (documentation) file|.
Methods are said to be **overloaded** when there
are multiple methods with the same name but a
-different **method signature**, where it requires a different number or type of parameters. For example, we have two different forward methods, forward() with no parameters and forward(100) which has a parameter that tells it how much to move forward. If there is more than one parameter, then the values given to the method need to correspond to the order and types in the method signature.
+different **method signature**, where it requires a different number or type of parameters. For example, we have two different forward methods, forward() with no parameters and forward(100) which has a parameter that tells it how much to move forward. If there is more than one parameter, then the values given to the method need to correspond to the order and types in the method signature.
|CodingEx| **Coding Exercise**
-(If the code below does not work in your browser, you can also use the Turtle code at this |repl link| (refresh page after forking and if it gets stuck) or download the files |github| to use in your own IDE.)
+(If the code below does not work in your browser, you can also use the Turtle code in |JuiceMind| or |replit| or download the files |github| to use in your own IDE.)
.. activecode:: TurtleTestMethods1
@@ -110,41 +133,62 @@ different **method signature**, where it requires a different number or type of
:datafile: turtleClasses.jar
1. Can you make yertle draw a square and change the pen color for each side of the square? Try something like: yertle.setColor(Color.red); This uses the |Color| class in Java which has some colors predefined like red, yellow, blue, magenta, cyan. You can also use more specific methods like setPenColor, setBodyColor, and setShellColor.
- 2. Can you draw a triangle? The turnRight() method always does 90 degree turns, but you'll need 60 degree angles for a equilateral triangle. Use the turn method which has a parameter for the angle of the turn in degrees. For example, turn(90) is the same as turnRight(). Try drawing a triangle with different colors.
+ 2. Can you draw a triangle? The turnRight() method always does 90 degree turns, but you'll need external angles of 120 degree for an equilateral triangle. Use the turn method which has a parameter for the angle of the turn in degrees. For example, turn(90) is the same as turnRight(). Try drawing a triangle with different colors.
~~~~
- import java.util.*;
import java.awt.*;
+ import java.util.*;
public class TurtleTestMethods1
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
-
- yertle.forward(100);
- yertle.turnLeft();
- yertle.forward(75);
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ Turtle yertle = new Turtle(world);
+
+ yertle.forward(100);
+ yertle.turnLeft();
+ yertle.forward(75);
+
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleTestMethods1");
}
@Test
public void test1()
{
- String orig = "import java.util.*;\nimport java.awt.*;\n\npublic class TurtleTestMethods1\n{\n public static void main(String[] args)\n {\n World world = new World(300,300);\n Turtle yertle = new Turtle(world);\n\n yertle.forward(100);\n yertle.turnLeft();\n yertle.forward(75);\n\n world.show(true);\n }\n}\n";
- boolean passed = codeChanged(orig);
+ boolean passed = codeChanged(
+ "import java.awt.*;\n" +
+ "import java.util.*;\n" +
+ "\n" +
+ "public class TurtleTestMethods1\n" +
+ "{\n" +
+ " public static void main(String[] args)\n" +
+ " {\n" +
+ " World world = new World(300, 300);\n" +
+ " Turtle yertle = new Turtle(world);\n" +
+ "\n" +
+ " yertle.forward(100);\n" +
+ " yertle.turnLeft();\n" +
+ " yertle.forward(75);\n" +
+ "\n" +
+ " world.show(true);\n" +
+ " }\n" +
+ "}\n"
+ );
assertTrue(passed);
}
@@ -154,8 +198,8 @@ different **method signature**, where it requires a different number or type of
String code = getCode();
int numColors = countOccurences(code, "Color(");
- boolean passed = numColors >= 4;
- passed = getResults("4 or more", ""+numColors, "Changing color at least 4 times", passed);
+ boolean passed = numColors >= 3;
+ passed = getResults("3 or more", "" + numColors, "Changes color at least 3 times", passed);
assertTrue(passed);
}
@@ -165,8 +209,8 @@ different **method signature**, where it requires a different number or type of
String code = getCode();
int numTurns = countOccurences(code, ".turn");
- boolean passed = numTurns >= 4;
- passed = getResults("4 or more", ""+numTurns, "Number of turns", passed);
+ boolean passed = numTurns >= 3;
+ passed = getResults("3 or more", "" + numTurns, "Turns at least 3 times", passed);
assertTrue(passed);
}
@@ -177,7 +221,7 @@ different **method signature**, where it requires a different number or type of
int numTurns = countOccurences(code, ".turn(");
boolean passed = numTurns >= 1;
- passed = getResults("1 or more", ""+numTurns, "Calls to turn(...)", passed);
+ passed = getResults("1 or more", "" + numTurns, "Calls to turn(...)", passed);
assertTrue(passed);
}
@@ -188,13 +232,11 @@ different **method signature**, where it requires a different number or type of
int numForward = countOccurences(code, ".forward(");
boolean passed = numForward >= 4;
- passed = getResults("4 or more", ""+numForward, "Calls to forward()", passed);
+ passed = getResults("4 or more", "" + numForward, "Calls to forward()", passed);
assertTrue(passed);
}
}
-
-
|CodingEx| **Coding Exercise**
Try the following mixed up code to draw a simple house made of a square and a triangle roof.
@@ -203,15 +245,15 @@ Try the following mixed up code to draw a simple house made of a square and a tr
:width: 200px
:align: left
:alt: simple house
-
-
+
+
.. parsonsprob:: DrawAHouse
:numbered: left
:practice: T
:adaptive:
:noindent:
-
- The following code uses a turtle to draw a simple house, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw a square for the house and then a red triangle for the roof. Click on the "Check Me" button to check your solution. You can copy and paste this code in the Active Code window above to see it in action.
+
+ The following code uses a turtle to draw a simple house, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw a square for the house and then a red triangle for the roof. Click on the "Check Me" button to check your solution. You can type this code in the Active Code window above to see it in action.
-----
public class TurtleDrawHouse
{
@@ -248,12 +290,12 @@ Try the following mixed up code to draw a simple house made of a square and a tr
}
=====
}
-
+
Tracing Methods
-----------------
-You will not write your own methods until Unit 5, but you should be able to trace and interpret method calls like below.
+You will not write your own methods until Unit 5, but you should be able to trace and interpret method calls like below.
Here is another version of the Old MacDonald Song with a more powerful abstraction. The method verse has 2 parameters for the animal and the noise it makes, so that it can be used for any animal.
Use the Code Lens button or this |Java Visualizer| to step through the code.
@@ -261,18 +303,18 @@ Use the Code Lens button or this |Java Visualizer| to step through the code.
.. |Java visualizer| raw:: html
Java visualizer
-
+
.. activecode:: SongFarm
:language: java
:autograde: unittest
:practice: T
-
+
Add another verse in main that calls the method verse with a different animal and noise.
~~~~
- public class Song
- {
-
- public void verse(String animal, String noise)
+ public class Song
+ {
+
+ public void verse(String animal, String noise)
{
System.out.println("Old MacDonald had a farm");
chorus();
@@ -283,63 +325,87 @@ Use the Code Lens button or this |Java Visualizer| to step through the code.
System.out.println("Old MacDonald had a farm");
chorus();
}
+
public void chorus()
{
System.out.println("E-I-E-I-O");
}
- public static void main(String[] args)
+ public static void main(String[] args)
{
- Song s = new Song();
- s.verse("cow", "moo");
- s.verse("duck","quack");
+ Song s = new Song();
+ s.verse("cow", "moo");
+ s.verse("duck", "quack");
}
}
- ====
- import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- public String expected = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a cow\nE-I-E-I-O\nWith a moo moo here,\nAnd a moo moo there,\nOld MacDonald had a farm\nE-I-E-I-O\nOld MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a duck\nE-I-E-I-O\nWith a quack quack here,\nAnd a quack quack there,\nOld MacDonald had a farm\nE-I-E-I-O";
-
- public RunestoneTests() {
- super("Song");
- }
-
- @Test
- public void test1()
- {
- String output = getMethodOutput("main");
-
- boolean passed = output.contains(expected);
-
- passed = getResults(expected, output, "Still have the old output", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test2()
- {
- String output = getMethodOutput("main");
-
- boolean passed = output.contains(expected) && !output.equals(expected);
-
- passed = getResults(expected, output, "Verse added", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test3()
- {
- String code = getCode();
- int numVerses = countOccurences(code, "verse(");
- boolean passed = numVerses >= 3;
- passed = getResults("3 or more", ""+numVerses, "Number of verses", passed);
- assertTrue(passed);
- }
- }
+ ====
+ // Test for 2.4.4 Song
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public String verse1 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a cow\nE-I-E-I-O\nWith a moo moo here,\nAnd a moo moo there,\nOld MacDonald had a farm\nE-I-E-I-O";
+ public String verse2 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a duck\nE-I-E-I-O\nWith a quack quack here,\nAnd a quack quack there,\nOld MacDonald had a farm\nE-I-E-I-O";
+
+ public String verse3 = "Old MacDonald had a farm\nE-I-E-I-O\nAnd on that farm he had a ...\nE-I-E-I-O\nWith a ... ... here,\nAnd a ... ... there,\nOld MacDonald had a farm\nE-I-E-I-O";
+
+ public RunestoneTests() {
+ super("Song");
+ }
+
+ @Test
+ public void test1()
+ {
+ String output = getMethodOutput("main");
+ output = output.replace(verse1, "").trim();
+ output = output.replace(verse2, "").trim();
+
+ boolean passed = output.length() > 0;
+
+ passed = getResults(verse3, output, "Contains new verse", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String output = getMethodOutput("main");
+
+ boolean passed1 = output.contains(verse1);
+ boolean passed2 = output.contains(verse2);
+ boolean passed = passed1 && passed2;
+
+ String exp = "Verse 1: true\nVerse 2: true";
+ String act = "Verse 1: " + passed1 + "\nVerse 2: " + passed2;
+
+ passed = getResults(exp, act, "Contains original verses", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCode1() {
+ String[] lines = getCode().split("\n");
+ String expect = "s.verse(";
+ String output = "";
+ int count = 0;
+
+ for (int i = 0; i < lines.length; i++) {
+ if (lines[i].contains(expect)) {
+ output += lines[i].trim() + "\n";
+ count++;
+ }
+ }
+
+ String expected = "s.verse(\"cow\", \"moo\");\ns.verse(\"duck\",\"quack\");\ns.verse(\"...\", \"...\");";
+
+ boolean passed = count >= 3;
+ passed = getResults(expected, output, "Added third call to verse", passed);
+ assertTrue(passed);
+ }
+ }
|Exercise| **Check your understanding**
@@ -356,29 +422,31 @@ Use the Code Lens button or this |Java Visualizer| to step through the code.
:feedback_c: The square(x) method is called before the divide(x,y) method.
:feedback_d: The main method prints out " and " in between the method calls.
:feedback_e: Try the code in the visualizer link below.
-
+
What does the following code print out?
-
+
.. code-block:: java
-
- public class MethodTrace
- {
- public void square(int x)
- {
- System.out.print(x*x);
- }
- public void divide(int x, int y)
- {
- System.out.println(x/y);
- }
- public static void main(String[] args) {
- MethodTrace traceObj = new MethodTrace();
- traceObj.square(5);
- System.out.print(" and ");
- traceObj.divide(4,2);
- }
- }
+ public class MethodTrace
+ {
+ public void square(int x)
+ {
+ System.out.print(x * x);
+ }
+
+ public void divide(int x, int y)
+ {
+ System.out.println(x / y);
+ }
+
+ public static void main(String[] args)
+ {
+ MethodTrace traceObj = new MethodTrace();
+ traceObj.square(5);
+ System.out.print(" and ");
+ traceObj.divide(4, 2);
+ }
+ }
.. |visualization| raw:: html
@@ -393,22 +461,27 @@ Try this |visualization| to see this code in action.
:width: 200px
:align: left
:alt: simple house
-
-This creative challenge is fun to do collaboratively in pairs. Design a house and have the turtle draw it with different colors below (or with this |repl link|). Can you add windows and a door? Come up with your own house design as a team.
-To draw a window, you will need to do penUp() to walk the turtle into position, for example:
+This creative challenge is fun to do collaboratively in pairs. Design a house and have the turtle draw it with different colors below (or on |JuiceMind| or |replit|). Can you add windows and a door? Come up with your own house design as a team.
+
+To draw a window, you will need to call ``penUp`` to walk the turtle into position, for example:
-.. code-block:: java
+.. code-block:: java
builder.penUp();
builder.moveTo(120,200);
builder.penDown();
-
+
It may help to act out the code pretending you are the turtle. Remember that the angles you turn depend on which direction you are facing, and the turtle begins facing up.
-.. |repl link| raw:: html
+.. |JuiceMind| raw:: html
+
+ JuiceMind
+
- repl.it link
+.. |replit| raw:: html
+
+ replit
.. activecode:: challenge2-4-TurtleHouse
@@ -416,35 +489,49 @@ It may help to act out the code pretending you are the turtle. Remember that the
:autograde: unittest
:datafile: turtleClasses.jar
- import java.util.*;
+ Draw a Turtle House! Make sure you use forward, turn, penUp, penDown, moveTo methods as well as different colors. Have fun!
+ ~~~~
import java.awt.*;
+ import java.util.*;
public class TurtleHouse
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
-
-
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleHouse");
}
@Test
public void test1()
{
- String orig = "import java.util.*;\nimport java.awt.*;\n\npublic class TurtleHouse\n{\n public static void main(String[] args)\n {\n World world = new World(300,300);\n\n\n\n world.show(true);\n }\n}\n";
+ String orig =
+ "import java.awt.*;\n"
+ + "import java.util.*;\n"
+ + "public class TurtleHouse\n"
+ + "{\n"
+ + " public static void main(String[] args)\n"
+ + " {\n"
+ + " World world = new World(300,300);\n\n\n\n"
+ + " world.show(true);\n"
+ + " }\n"
+ + "}\n";
boolean passed = codeChanged(orig);
assertTrue(passed);
}
@@ -456,7 +543,7 @@ It may help to act out the code pretending you are the turtle. Remember that the
int num = countOccurences(code, "moveTo(");
boolean passed = num >= 1;
- passed = getResults("1 or more", ""+num, "Calls moveTo(...)", passed);
+ passed = getResults("1 or more", "" + num, "Calls moveTo(...)", passed);
assertTrue(passed);
}
@@ -467,7 +554,7 @@ It may help to act out the code pretending you are the turtle. Remember that the
int num = countOccurences(code, ".penUp()");
boolean passed = num >= 1;
- passed = getResults("4 or more", ""+num, "Calls penUp()", passed);
+ passed = getResults("1 or more", "" + num, "Calls penUp()", passed);
assertTrue(passed);
}
@@ -478,9 +565,10 @@ It may help to act out the code pretending you are the turtle. Remember that the
int num = countOccurences(code, ".penDown(");
boolean passed = num >= 1;
- passed = getResults("1 or more", ""+num, "Calls penDown()", passed);
+ passed = getResults("1 or more", "" + num, "Calls penDown()", passed);
assertTrue(passed);
}
+
@Test
public void test5()
{
@@ -488,7 +576,7 @@ It may help to act out the code pretending you are the turtle. Remember that the
int numTurns = countOccurences(code, ".turn");
boolean passed = numTurns >= 6;
- passed = getResults("6 or more", ""+numTurns, "turns", passed);
+ passed = getResults("6 or more", "" + numTurns, "turns", passed);
assertTrue(passed);
}
@@ -499,18 +587,17 @@ It may help to act out the code pretending you are the turtle. Remember that the
int numForward = countOccurences(code, ".forward(");
boolean passed = numForward >= 6;
- passed = getResults("6 or more", ""+numForward, "Calls to forward()", passed);
+ passed = getResults("6 or more", "" + numForward, "Calls to forward()", passed);
assertTrue(passed);
}
}
-
Summary
-------------------
-- **Methods** define the behaviors or functions for objects.
+- **Methods** define the behaviors or functions for objects.
-- To use an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();**
+- To use an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();**
- Some methods take parameters/arguments that are placed inside the parentheses **object.method(arguments)**.
@@ -524,7 +611,7 @@ AP Practice
:practice: T
Consider the following methods:
-
+
.. code-block:: java
public void inchesToCentimeters(double i)
@@ -539,37 +626,37 @@ AP Practice
}
Assume that the method call ``inchesToCentimeters(10)`` appears in a method in the same class. What is printed as a result of the method call?
-
+
- inches --> centimeters
-
+
- The values of the variables inches and centimeters should be printed out, not the words.
-
+
- 10 --> 25
-
+
- Two doubles should be printed, not two ints, and the centimeters should be 25.4
-
+
- 25.4 --> 10
-
+
- Inches should be printed before centimeters.
-
+
- 10 --> 12.54
-
+
- c = 10 * 2.54 = 25.4, not 12.54.
-
+
- 10.0 --> 25.4
-
- + Correct! centimeters = 10 * 2.54 = 25.4.
+
+ + Correct! centimeters = 10 * 2.54 = 25.4.
.. mchoice:: AP2-4-2
:practice: T
-
+
Consider the following methods, which appear in the same class.
.. code-block:: java
-
+
public void splitPizza(int numOfPeople)
{
int slicesPerPerson = 8/numOfPeople;
@@ -581,25 +668,24 @@ AP Practice
System.out.println("Each person gets " + slices + " slices each");
}
- Which of the following lines would go into ``/* INSERT CODE HERE */`` in the method splitPizza in order to call the ``printSlices`` method to print the number of slices per person correctly?
-
+ Which of the following lines would go into ``/* INSERT CODE HERE */`` in the method splitPizza in order to call the ``printSlices`` method to print the number of slices per person correctly?
+
- printSlices(slicesPerPerson);
-
+
+ Correct! If you had 4 people, slicesPerPerson would be 8/4=2 and printSlices would print out "Each person gets 2 slices each".
-
+
- printSlices(numOfPeople);
-
+
- If you had 4 people, this would print out that they get 4 slices each of an 8 slice pizza.
-
+
- printSlices(8);
-
+
- This would always print out 8 slices each.
-
+
- splitPizza(8);
-
+
- This would not call the printSlices method.
-
+
- splitPizza(slicesPerPerson);
-
- - This would not call the printSlices method.
+ - This would not call the printSlices method.
diff --git a/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst b/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst
index 441db704d..4a83e8c8e 100644
--- a/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst
+++ b/_sources/Unit2-Using-Objects/topic-2-5-methods-return.rst
@@ -1,30 +1,15 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 2-5-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-.. index::
- single: method
+.. index::
+ single: method
single: parameter
single: argument
single: return
-
+
.. |runbutton| image:: Figures/run-button.png
:height: 30px
:align: top
@@ -32,27 +17,69 @@
.. |repl link| raw:: html
- repl.it link
+ replit.com link
.. |github| raw:: html
here
-
-Calling Methods that Return Values
-===================================
-
-If a method is a **void method** and has **void** as its return type, like most of the methods we have seen so far, that means that it does not return anything. But some methods **return** a value back that the program can use.
-
-Get Methods
-------------
-
-In the previous lesson, we used some set methods with parameters to set the attributes of a turtle to different values, for example yertle.setColor(Color.red); or yertle.setWidth(50); Programmers create get and set methods for each attribute represented as an instance variable in a class to access and modify the value in that variable. The get methods always return back the value of that instance variable, and the set methods modify the value.
-
-When you use a get method, you need to save what it returns in a variable or use the value in some way for example by printing it out. The data type of the variable must match the data type of the return value of the method. You can find out the return type of a method in its documentation. It will be right before the method name, for example *int getWidth()* means getWidth will return an int (an integer number).
-Here are some examples of using get methods for the turtle object yertle.
-
-.. code-block:: java
+|Time45|
+
+Methods that Return Values
+==========================
+
+All the methods on ``Turtle`` that we’ve discussed so far have had a ``void``
+return type. Such methods are sometimes called **void methods**. Because a
+``void`` method doesn’t return any value, the only point of calling one is
+because it does something that can be observed by the user or by other code—it
+changes the state of the object or maybe causes something to happen like drawing
+a line on the screen. Or both. These things they do are sometimes called
+“effects”.
+
+In contrast, methods with a return type of anything `other` than ``void`` are
+called **non-void** methods. These methods **return** a value that the code
+calling the method can use. And because methods are called on an object, these
+methods can be used to return values that tell us things about an object’s
+internal state.
+
+In well-designed programs, non-void methods typically don’t have effects; they
+just compute and return a value. And void methods obviously can’t return values.
+So most methods are of one kind or the other: either a void method which is
+called for some effect or a non-void method that is called to compute a value
+but otherwise has no effect. To put it another way, void methods `do things`
+while non-void methods `produce values`.
+
+
+Accessors / Getters
+-------------------------
+
+A simple kind of method that returns a value is what is formally called an
+**accessor** because it accesses a value in an object. In the real world
+everyone calls them **getters**. A getter is a method that takes no arguments
+and has a non-\ ``void`` return type. In Java they are almost always named
+something that starts with ``get``, and they usually just return the value of one
+of the object’s instance variables. For example, the ``Turtle`` class has
+several getters, ``getWidth`` and ``getHeight`` which return the width and the
+height of a ``Turtle`` object and ``getXPos`` and ``getYPos`` which return the x
+and y values of the ``Turtle``\ ’s position.
+
+That means that after you construct a ``Turtle``, either at the default position
+in the middle of the ``World`` or by specifying a starting point as arguments to
+the constructor, you don’t need to keep track of where you put it; you can
+always get its current position with the ``getXPos`` and ``getYPos`` getters.
+Better yet, after creating a ``Turtle`` and moving it all around with the
+``forward`` and ``turn`` methods we discussed in the previous section, you don’t
+have to figure out where it ended up; you can just ask it for its new position,
+again with the ``getXPos`` and ``getYPos`` getters.
+
+Note that when you use a getter, you need to do something with the value it
+returns. You might assign it to a variable, use it in an expression, or print it
+out. If you don’t, you’re just getting a value and doing nothing with it—you
+might as well not have bothered to call the getter in the first place.
+
+Here are some examples of using getters on the ``Turtle`` object ``yertle``.
+
+.. code-block:: java
Turtle yertle = new Turtle(world);
int width = yertle.getWidth();
@@ -61,96 +88,135 @@ Here are some examples of using get methods for the turtle object yertle.
System.out.println("Yertle's height is: " + height);
System.out.println("Yertle's x position is: " + yertle.getXPos() );
System.out.println("Yertle's y position is: " + yertle.getYPos() );
-
+
.. note::
- A common error is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like saving it into a variable or printing it out.
+ A common error is forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out.
|CodingEx| **Coding Exercise:**
-
-
.. activecode:: TurtleTestGetSet
:language: java
:autograde: unittest
:datafile: turtleClasses.jar
- Try the code below that changes the turtle's width and height. How big or small can you make yertle?
+ Try the code below that creates a turtle and moves it around a bit. Can you
+ confirm that its new position matches what you’d expect given the movements
+ it made? Try changing where it moves to make sure.
+
+ (If the code below does not work in your browser, you can also copy in the
+ code below into the Turtle code at this |repl link| (refresh page after
+ forking and if it gets stuck) or download the files |github| to use in your
+ own IDE.)
- (If the code below does not work in your browser, you can also copy in the code below into the Turtle code at this |repl link| (refresh page after forking and if it gets stuck) or download the files |github| to use in your own IDE.)
~~~~
- import java.util.*;
import java.awt.*;
- import java.lang.Math;
-
+ import java.util.*;
+
public class TurtleTestGetSet
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
- System.out.println("Yertle's width is: " + yertle.getWidth());
- yertle.setWidth(200);
- yertle.setHeight(200);
- System.out.println("Yertle's width is: " + yertle.getWidth());
- yertle.turnRight();
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ Turtle yertle = new Turtle(world);
+ System.out.println(
+ "Yertle is starting at: "
+ + yertle.getXPos()
+ + ", "
+ + yertle.getYPos());
+ yertle.forward(100);
+ yertle.turn(90);
+ yertle.forward(50);
+ System.out.println(
+ "Yertle has ended up at: "
+ + yertle.getXPos()
+ + ", "
+ + yertle.getYPos());
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleTestGetSet");
}
@Test
public void test1()
{
- String orig = "import java.util.*;\nimport java.awt.*;\nimport java.lang.Math;\n\npublic class TurtleTestGetSet\n{\n public static void main(String[] args)\n {\n World world = new World(300,300);\n Turtle yertle = new Turtle(world);\n System.out.println(\"Yertle's width is: \" + yertle.getWidth());\n yertle.setWidth(200);\n yertle.setHeight(200);\n System.out.println(\"Yertle's width is: \" + yertle.getWidth());\n yertle.turnRight();\n world.show(true);\n }\n}\n";
+ String orig =
+ "import java.awt.*;\n"
+ + "import java.util.*;\n\n"
+ + "public class TurtleTestGetSet\n"
+ + "{\n"
+ + "public static void main(String[] args)\n"
+ + "{\n"
+ + "World world = new World(300,300);\n"
+ + "Turtle yertle = new Turtle(world);\n"
+ + "System.out.println(\"Yertle is starting at: \" + yertle.getXPos() + \", \" +"
+ + " yertle.getYPos());\n"
+ + "yertle.forward(100);\n"
+ + "yertle.turn(90);\n"
+ + "yertle.forward(50);\n"
+ + "System.out.println(\"Yertle has ended up at: \" + yertle.getXPos() + \", \" +"
+ + " yertle.getYPos());\n"
+ + "world.show(true);\n"
+ + "}\n"
+ + "}\n";
boolean passed = codeChanged(orig);
assertTrue(passed);
}
}
-
-|CodingEx| **Coding Exercise:**
+
+|CodingEx| **Coding Exercise:**
.. activecode:: TurtleArea
:language: java
:autograde: unittest
:datafile: turtleClasses.jar
- Fix the errors in the code below so that it prints out the area of the space that the turtle occupies by multiplying its width and height. Remember that you have to do something with the values that the get methods return.
+ Fix the errors in the code below so that it prints out the area of the space
+ that the turtle occupies by multiplying its width and height. Remember that
+ you have to do something with the values that the get methods return.
+
~~~~
- import java.util.*;
import java.awt.*;
- import java.lang.Math;
-
+ import java.lang.Math;
+ import java.util.*;
+
public class TurtleArea
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
-
- int area;
- yertle.getWidth() * getHeight;
- System.out.println("Yertle's area is: ");
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300,300);
+ Turtle yertle = new Turtle(world);
+
+ int area;
+ yertle.getWidth() * getHeight;
+ System.out.println("Yertle's area is: ");
+ }
}
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleArea");
}
@@ -162,21 +228,35 @@ Here are some examples of using get methods for the turtle object yertle.
boolean passed = getResults(expected, actual, "Prints correct answer");
assertTrue(passed);
}
- }
-toString() Methods
-------------------
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = ".getHeight()";
-Another common method that returns a value is the **toString()** method. This method is called automatically to try to convert an object to a String when it is needed, for example in a print statement. In the Turtle class, the toString() method returns a String description of the turtle.
+ int num = countOccurences(code, target);
-.. code-block:: java
+ boolean passed = num >= 1;
- Turtle yertle = new Turtle(world);
- yertle.setName("yertle"); // set name before you use toString()
- System.out.println(yertle.toString());
- // Or you can just use the object here and it will call toString() automatically!
- System.out.println(yertle);
+ getResults("1+", "" + num, "Calls to " + target, passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String code = getCode();
+ String target = ".getWidth()";
+
+ int num = countOccurences(code, target);
+
+ boolean passed = num >= 1;
+ getResults("1+", "" + num, "Calls to " + target, passed);
+ assertTrue(passed);
+ }
+ }
|CodingEx| **Coding Exercise:**
@@ -185,34 +265,38 @@ Another common method that returns a value is the **toString()** method. This me
:autograde: unittest
:datafile: turtleClasses.jar
- Try some of the get methods and the toString() method in the program below. Note that you have to print out what the get methods return in order to see what they do!
+ Try some of the ``Turtle`` getters in the program below. Remember that you
+ have to print out the values the getters return in order to see them!
+ Calling a getter just gets a value; it’s up to you to do something with it.
+
~~~~
- import java.util.*;
import java.awt.*;
- import java.lang.Math;
-
+ import java.util.*;
+
public class TurtleTestMethods2
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
-
- // Try some get methods here!
-
-
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ Turtle yertle = new Turtle(world);
+
+ // Try some get methods here!
+
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleTestMethods2");
}
@@ -223,7 +307,7 @@ Another common method that returns a value is the **toString()** method. This me
int num = countOccurences(code, "getWidth()");
boolean passed = num > 0;
- getResults(">=1", "" + num, "Calls to getWidth()");
+ getResults(">=1", "" + num, "Calls to getWidth()", passed);
assertTrue(passed);
}
@@ -234,26 +318,37 @@ Another common method that returns a value is the **toString()** method. This me
int num = countOccurences(code, "getHeight()");
boolean passed = num > 0;
- getResults(">=1", "" + num, "Calls to getHeight()");
- assertTrue(passed);
- }
-
- @Test
- public void test3()
- {
- String code = getCode();
- int num = countOccurences(code, "toString()") + countOccurences(code, "System.out.println(yertle)");
-
- boolean passed = num > 0;
- getResults(">=1", "" + num, "Calls to toString()");
+ getResults(">=1", "" + num, "Calls to getHeight()", passed);
assertTrue(passed);
}
}
-Methods with Arguments and Return Values
+Methods with Arguments and a Return Value
-----------------------------------------
-Methods that take arguments and return values are like mathematical functions. Given some input, they return a value. For example, a square(x) method would take an argument x and return its square by multiplying it by itself.
+Since getters take no arguments, all they can do is return a value based on the
+current state of the object. But often it’s useful to have methods that compute
+values based on both the current state of the object and some arguments.
+
+For example, while we could use a ``Turtle``\ ’s ``getXPos`` and ``getYPos``
+getters and some math (remember your Pythagorean Theorem?) to figure out how far
+away a ``Turtle`` is from any given point, if that’s a thing we need to do in
+a lot of programs using ``Turtle``, it might be nice to be able to ask a
+``Turtle`` directly for its distance from a given point. After all, it knows
+where it is, so why not do the math for us?
+
+And indeed, the ``Turtle`` class has a method called ``getDistance`` that takes
+two ``int`` arguments representing an `x` value and a `y` value and returns the
+distance between the ``Turtle``\ ’s current position and that `x,y` point. This
+is not a getter because it doesn’t just get an existing value; it computes a new
+value based on the arguments it is passed as well as the state of the ``Turtle``.
+
+Methods that take arguments and return values are somewhat like mathematical
+functions. Given some input, they return a value. (Mathematicians expect that a
+function always returns the same value, given the same arguments. So they would
+not consider something like ``getDistance(x, y)`` a true function since its
+return value also depends on the current position of the ``Turtle``. But we’re
+doing programming, not math.)
.. figure:: Figures/function.png
:width: 400px
@@ -263,10 +358,123 @@ Methods that take arguments and return values are like mathematical functions. G
Figure 1: Method that takes arguments and returns a value
-You will not write your own methods until Unit 5, but you should be able to trace through method calls like below. Notice that the **return statement** in a method returns the value that is indicated in the return type back to the calling method. The calling method must save or use or print that value.
+We will save a deeper discussion of actually writing getters and other methods
+until Unit 5, but for the AP progress checks for this unit, you should be able to
+trace through method calls like the ones below. Notice that the **return
+statement** in a method returns the value, and it must match declared return type
+of the method. The calling method must then do something useful with that value.
|Exercise| **Check your understanding**
+.. |visualization1| raw:: html
+
+ visualization
+
+.. |visualization2| raw:: html
+
+ visualization
+
+.. |visualization3| raw:: html
+
+ visualization
+
+
+.. mchoice:: traceCircleArea
+ :practice: T
+ :answer_a: 0
+ :answer_b: 314.159
+ :answer_c: c.getArea()
+ :answer_d: The code will not compile.
+ :answer_e: 100.0
+ :correct: b
+ :feedback_a: First, call the constructor, then call getArea().
+ :feedback_b: Correct! getArea() returns 3.14159 * radius * radius, where radius is set to 10 by the constructor.
+ :feedback_c: c.getArea() is a method call, not a value.
+ :feedback_d: The code does compile.
+ :feedback_e: Don't forget to multiply by 3.14159.
+
+ Consider the following class definition.
+
+ .. code-block:: java
+
+ public class Circle
+ {
+ private double radius;
+
+ public Circle(double r)
+ {
+ radius = r;
+ }
+
+ public double getArea()
+ {
+ return 3.14159 * radius * radius;
+ }
+ }
+
+ Assume that the following code segment appears in a main method.
+
+ .. code-block:: java
+
+ Circle c = new Circle(10);
+ System.out.println(c.getArea());
+
+ What is printed as a result of executing the code segment? (If you get stuck, try this |visualization1| to see this code in action.)
+
+
+.. mchoice:: traceRectangleArea
+ :practice: T
+ :answer_a: 150
+ :answer_b: 150.0
+ :answer_c: 225
+ :answer_d: 255.0
+ :answer_e: 0
+ :correct: c
+ :feedback_a: Note that the method resize() is called before getArea().
+ :feedback_b: Note that the method resize() is called before getArea().
+ :feedback_c: Correct! resize() increases the width by 5, so the area is 15 * 15 = 225.
+ :feedback_d: Note that getArea() returns an int
+ :feedback_e: Note that the constructor initializes width and height.
+
+ Consider the following class definition.
+
+ .. code-block:: java
+
+ public class Rectangle
+ {
+ private int width;
+ private int height;
+
+ public Rectangle(int w, int h)
+ {
+ width = w;
+ height = h;
+ }
+
+ public void resize(int amt)
+ {
+ width += amt;
+ }
+
+ public int getArea()
+ {
+ return width * height;
+ }
+ }
+
+
+ Assume that the following code segment appears in a main method.
+
+ .. code-block:: java
+
+ Rectangle r = new Rectangle(10, 15);
+ r.resize(5);
+ System.out.println(r.getArea());
+
+
+ What is printed as a result of executing the code segment? (If you get stuck, try this |visualization2| to see this code in action.)
+
+
.. mchoice:: traceReturnMethods
:practice: T
:answer_a: 5
@@ -278,76 +486,82 @@ You will not write your own methods until Unit 5, but you should be able to trac
:feedback_a: Make sure you call both methods and compute the square of 2 and then add the results.
:feedback_b: Yes, square(2) returns 4 which is added to divide(6,2) which returns 3. The total of 4 + 3 is 7.
:feedback_c: Make sure you add the results before printing it out.
- :feedback_d: Make sure you square(2) and add the results before printint it out.
+ :feedback_d: Make sure you square(2) and add the results before printing it out.
:feedback_e: Try the code in an active code window.
-
- What does the following code print out?
-
+
+ What does the following code print out? (If you get stuck, try this |visualization3| to see this code in action.)
+
.. code-block:: java
-
- public class MethodTrace
+
+ public class MethodTrace
{
- public int square(int x)
- {
- return x*x;
- }
- public int divide(int x, int y)
- {
- return x/y;
- }
- public static void main(String[] args) {
- MethodTrace traceObj = new MethodTrace();
- System.out.println( traceObj.square(2) + traceObj.divide(6,2) );
- }
- }
+ public int square(int x)
+ {
+ return x * x;
+ }
+
+ public int divide(int x, int y)
+ {
+ return x / y;
+ }
+
+ public static void main(String[] args)
+ {
+ MethodTrace traceObj = new MethodTrace();
+ System.out.println(traceObj.square(2) + traceObj.divide(6, 2));
+ }
+ }
-.. |visualization| raw:: html
- visualization
-Try this |visualization| to see this code in action.
-
|Groupwork| Programming Challenge : Turtle Distances
----------------------------------------------------
-1. The Turtle class has a method called getDistance(x,y) which will return the turtle's distance from a point (x,y). Can you find yertle's distance from the point (0,0)?
+1. As we mentioned above, ``Turtle`` class has a method called
+ ``getDistance(x,y)`` which will return the turtle's distance from a point
+ (x,y). Can you find yertle's distance from the point (0,0)?
-2. Add another turtle and make both turtles move. Then find the distance between them. You must use the getXPos() and getYPos() methods as well as the getDistance() method.
+2. Add another turtle and make both turtles move. Then find the distance between
+ them. You must use the ``getXPos`` and ``getYPos`` methods as well as the
+ ``getDistance`` method.
.. activecode:: challenge2-5-TurtleDistance
:language: java
:autograde: unittest
:datafile: turtleClasses.jar
- import java.util.*;
+ Use the ``getXPos``, ``getYPos``, and ``getDistance(x,y)`` methods to find yertle's distance from the point (0,0). Add another turtle, move both turtles to different positions, and find the distance between the two turtles.
+ ~~~~
import java.awt.*;
- import java.lang.Math;
-
+ import java.util.*;
+
public class TurtleTestDistance
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
-
- // Can you find yertle's distance from the point (0,0)?
-
- // Can you find the distance between 2 turtles?
-
-
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ Turtle yertle = new Turtle(world);
+
+ // Can you find yertle's distance from the point (0,0)?
+
+ // Can you find the distance between 2 turtles?
+
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleTestDistance");
}
@@ -358,7 +572,7 @@ Try this |visualization| to see this code in action.
int num = countOccurences(code, ".getXPos()");
boolean passed = num > 0;
- getResults(">=1", "" + num, "Calls to getXPos()");
+ getResults(">=1", "" + num, "Calls to getXPos()", passed);
assertTrue(passed);
}
@@ -369,7 +583,7 @@ Try this |visualization| to see this code in action.
int num = countOccurences(code, ".getYPos()");
boolean passed = num > 0;
- getResults(">=1", "" + num, "Calls to getYPos()");
+ getResults(">=1", "" + num, "Calls to getYPos()", passed);
assertTrue(passed);
}
@@ -380,7 +594,7 @@ Try this |visualization| to see this code in action.
int num = countOccurences(code, ".getDistance(");
boolean passed = num >= 2;
- getResults(">=2", "" + num, "Calls to getDistance(...)");
+ getResults(">=2", "" + num, "Calls to getDistance(...)", passed);
assertTrue(passed);
}
@@ -391,24 +605,34 @@ Try this |visualization| to see this code in action.
int num = countOccurences(code, ".getDistance(0,0)");
boolean passed = num >= 1;
- getResults(">=1", "" + num, "Calls getDistance(0,0)");
+ getResults(">=1", "" + num, "Calls getDistance(0,0)", passed);
assertTrue(passed);
}
}
-
Summary
-------------------
-- Some methods return values.
-- To use the return value when calling a method, it must be stored in a variable or used as part of an expression. The variable data type must match the return type of the method.
+- Non-void methods are methods that return values.
+
+- Non-void methods typically do not have effects, and are called purely for the
+ value they return.
+
+- It is up to the caller of a non-void method to do something with the return
+ value, such as assigning it to a variable or using it as part of an
+ expression.
+
+- The value returned by a method has to match the declared return type of the
+ method. Thus it can only be used where a value of that type is allowed, such
+ as being assigned to a variable of that type. data type must match the return
+ type of the method.
AP Practice
-------------
.. mchoice:: AP2-5-1
:practice: T
-
+
Consider the following method.
.. code-block:: java
@@ -417,27 +641,27 @@ AP Practice
{ /*implementation not shown */}
Which of the following lines of code, if located in a method in the same class as calculatePizzaBoxes, will compile without an error?
-
+
- int result = calculatePizzaBoxes(45, 9.0);
- The method calculatePizzaBoxes returns a double value that cannot be saved into an int variable.
-
+
- double result = calculatePizzaBoxes(45.0, 9.0);
-
+
- The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0.
- int result = calculatePizzaBoxes(45.0, 9);
-
+
- The method calculatePizzaBoxes has an int parameter that cannot hold a double value 45.0. Note that the int 9 can be passed into a double parameter.
-
+
- double result = calculatePizzaBoxes(45, 9.0);
-
+
+ The method calculatePizzaBoxes has an int and a double parameter and returns a double result.
-
+
- result = calculatePizzaBoxes(45, 9);
-
- - The variable result has not been declared (with an appropriate data type).
-
+
+ - The variable result has not been declared (with an appropriate data type).
+
.. mchoice:: AP2-5-2
:practice: T
@@ -468,31 +692,35 @@ AP Practice
}
Assume that the following code segment appears in a class other than Liquid.
-
+
.. code-block:: java
Liquid water = new Liquid();
water.lowerTemp();
System.out.println(water.getTemp());
- What is printed as a result of executing the code segment?
-
+ What is printed as a result of executing the code segment? (If you get stuck, try this |visualizationLiquid| to see this code in action.)
+
- \-10
-
- - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
-
+
+ - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
+
- 50
-
- - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
-
+
+ - The Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it.
+
- water.getTemp()
-
+
- The System.out.println will print the value returned from water.getTemp().
-
+
- The code will not compile.
-
+
- This code should compile.
- 40.0
-
- + Correct, the Liquid() constructor sets the currentTemp instance variable to 50 and the lowerTemp() method subtracts 10 from it, and getTemp() returns the currentTemp value as a double.
+
+ + Correct, the Liquid() constructor sets the currentTemp instance variable to 50, and the lowerTemp() method subtracts 10 from it, and getTemp() returns the currentTemp value as a double.
+
+.. |visualizationLiquid| raw:: html
+
+ visualization
diff --git a/_sources/Unit2-Using-Objects/topic-2-6-strings.rst b/_sources/Unit2-Using-Objects/topic-2-6-strings.rst
index 29827f6e1..5eaa4ea14 100644
--- a/_sources/Unit2-Using-Objects/topic-2-6-strings.rst
+++ b/_sources/Unit2-Using-Objects/topic-2-6-strings.rst
@@ -1,82 +1,67 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 2-6-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-.. highlight:: java
- :linenothreshold: 4
-
-
-.. index::
- single: String
- single: object reference
- single: reference
- pair: String; definition
-
+.. index::
+ single: String
+ single: object reference
+ single: reference
+ pair: String; definition
+
+|Time45|
Strings
========
-**Strings** in Java are objects of the ``String`` class that hold sequences of characters (a, b, c, $, etc). Remember that a class (or classification) in Java defines the data that all objects of the class have (the fields) and the behaviors, the things that objects know how to do (the methods).
+**Strings** in Java are objects of the ``String`` class that hold sequences of characters (a, b, c, $, etc). Remember that a class (or classification) in Java defines the data that all objects of the class have (the fields) and the behaviors, the things that objects know how to do (the methods).
-You can declare a variable to be of type ``String``.
+You can declare a variable to be of type ``String``.
.. note::
- Class names in Java, like ``String``, begin with a capital letter. All primitive types: ``int``, ``double``, and ``boolean``, begin with a lowercase letter. This is one easy way to tell the difference between primitive types and class types.
+ Class names in Java, like ``String``, begin with a capital letter. All primitive types: ``int``, ``double``, and ``boolean``, begin with a lowercase letter. This is one easy way to tell the difference between primitive types and class types.
.. activecode:: lcsb1
:language: java
:autograde: unittest
-
+
Run the following code. What does it print?
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- String greeting = null;
- System.out.println(greeting);
- }
+ public static void main(String[] args)
+ {
+ String greeting = null;
+ System.out.println(greeting);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "null";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-The code above declares an object variable named ``greeting`` and sets the value of greeting to the Java keyword ``null`` to show that it doesn't refer to any object yet. So ``System.out.println(greeting);`` will print ``null``.
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "null";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
-Object variables **refer** to objects in memory. A reference is a way to find the actual object, like adding a contact to your phone lets you reach someone without knowing exactly where they are. The value of greeting is null since the string object has not been created yet.
+The code above declares an object variable named ``greeting`` and sets the value of greeting to the Java keyword ``null`` to show that it doesn't refer to any object yet. So ``System.out.println(greeting);`` will print ``null``.
+
+Object variables **refer** to objects in memory. A reference is a way to find the actual object, like adding a contact to your phone lets you reach someone without knowing exactly where they are. The value of greeting is null since the string object has not been created yet.
.. figure:: Figures/greeting.png
:width: 50px
@@ -84,28 +69,28 @@ Object variables **refer** to objects in memory. A reference is a way to find t
:figclass: align-center
Figure 1: Initial value for an object reference
-
-.. index::
- pair: String; creation
+
+.. index::
+ pair: String; creation
In Java there are two ways to create an object of the ``String`` class. You can use the ``new`` keyword followed by a space and then the class constructor and then in parentheses you can include values used to initialize the fields of the object. This is the standard way to create a new object of a class in Java.
.. code-block:: java
- greeting = new String("Hello");
-
-.. index::
+ String greeting = new String("Hello");
+
+.. index::
single: String literal
- pair: String; literal
-
-
-In Java you can also use just a **string literal**, which is a set of characters enclosed in double quotes (``"``), to create a ``String`` object.
+ pair: String; literal
-.. code-block:: java
- greeting = "Hello";
+In Java you can also use just a **string literal**, which is a set of characters enclosed in double quotes (``"``), to create a ``String`` object.
+
+.. code-block:: java
-In both cases an object of the ``String`` class will be created in memory and the value of the variable greeting will be set to an object reference, a way to find that object.
+ String greeting = "Hello";
+
+In both cases an object of the ``String`` class will be created in memory and the value of the variable greeting will be set to an object reference, a way to find that object.
|CodingEx| **Coding Exercise:**
@@ -114,79 +99,87 @@ In both cases an object of the ``String`` class will be created in memory and th
:language: java
:autograde: unittest
- Here is an active code sample that creates two greeting strings: one using a string literal and the other using new and the String constructor. Change the code to add 2 new strings called firstname and lastname, one using a string literal and the other using new, and print them out with the greetings.
+ Here is an active code sample that creates two greeting strings: one using a string literal and the other using new and the String constructor. Change the code to add 2 new strings called firstName and lastName, one using a string literal and the other using new, and print them out with the greetings.
~~~~
public class StringTest
{
- public static void main(String[] args)
- {
- String greeting1 = "Hello!";
- String greeting2 = new String("Welcome!");
- System.out.println(greeting1);
- System.out.println(greeting2);
+ public static void main(String[] args)
+ {
+ String greeting1 = "Hello!";
+ String greeting2 = new String("Welcome!");
+ System.out.println(greeting1);
+ System.out.println(greeting2);
}
- }
+ }
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
@Test
- public void testChangedCode() {
- String origCode = "public class StringTest { public static void main(String[] args) { String greeting1 = \"Hello!\"; String greeting2 = new String(\"Welcome!\");System.out.println(greeting1); System.out.println(greeting2); } }";
+ public void testChangedCode()
+ {
+ String origCode =
+ "public class StringTest { public static void main(String[] args) {"
+ + " String greeting1 = \"Hello!\"; String greeting2 = new"
+ + " String(\"Welcome!\"); System.out.println(greeting1);"
+ + " System.out.println(greeting2); } }";
boolean changed = codeChanged(origCode);
assertTrue(changed);
}
}
-
-
-
.. activecode:: lcsb2
:language: java
:autograde: unittest
-
- Now that greeting refers to an actual object we can ask the object what class created it. Try the following. What does it print?
+
+ Now that greeting refers to an actual object we can ask the object what class created it. Try the following. What does it print?
~~~~
public class Test2
{
- public static void main(String[] args)
- {
- String greeting = "Hello";
- Class currClass = greeting.getClass();
- System.out.println(currClass);
- Class parentClass = currClass.getSuperclass();
- System.out.println(parentClass);
- }
+ public static void main(String[] args)
+ {
+ String greeting = "Hello";
+ Class currClass = greeting.getClass();
+ System.out.println(currClass);
+ Class parentClass = currClass.getSuperclass();
+ System.out.println(parentClass);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "class java.lang.String\nclass java.lang.Object";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
-.. index::
- single: parent class
- single: superclass
- single: inheritance
- single: package
- single: java.lang
- pair: package; java.lang
-The code above will first print ``class java.lang.String`` since ``greeting`` was created by the ``String`` class. The full name for the ``String`` class is ``java.lang.String``. The ``java.lang`` part is the **package** name. Every class in the Java language is in a package and the standard classes like ``String`` are in the ``java.lang`` package. Every object in Java knows the class that created it. Also, every class knows its **parent** class. Yes, a class can have a parent class, just as people have parents. But, in Java a class can only have one parent. A class can ``inherit`` object fields and methods from a parent class, just like you might inherit musical ability from a parent. The fourth line will print ``class java.lang.Object`` because the parent class (**superclass**) of the String class is the Object class. All classes in Java inherit from the Object class at some point in their ancestry.
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "class java.lang.String\nclass java.lang.Object";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
+.. index::
+ single: parent class
+ single: superclass
+ single: inheritance
+ single: package
+ single: java.lang
+ pair: package; java.lang
+
+The code above will first print ``class java.lang.String`` since ``greeting`` was created by the ``String`` class. The full name for the ``String`` class is ``java.lang.String``. The ``java.lang`` part is the **package** name. Every class in the Java language is in a package and the standard classes like ``String`` are in the ``java.lang`` package. Every object in Java knows the class that created it. Also, every class knows its **parent** class. Yes, a class can have a parent class, just as people have parents. But, in Java a class can only have one parent. A class can ``inherit`` object fields and methods from a parent class, just like you might inherit musical ability from a parent. The last print statement will print ``class java.lang.Object`` because the parent class (**superclass**) of the String class is the Object class. All classes in Java inherit from the Object class at some point in their ancestry.
.. figure:: Figures/stringObject.png
:width: 500px
@@ -194,55 +187,78 @@ The code above will first print ``class java.lang.String`` since ``greeting`` wa
:figclass: align-center
Figure 2: Object variable of type String with a reference to a String object which has a reference to the String class which has a reference to the Object class.
-
-
+
+
String Operators - Concatenation
--------------------------------
-.. index::
- pair: String; append
-
-Strings can be **appended** to each other to create a new string using the ``+`` or ``+=`` operator . This is also called **concatenation**.
+.. index::
+ pair: String; append
+
+``String``\ s can be added to each other to create a new string using the ``+``
+or ``+=`` operator . This is also called **appending** or **concatenating**. You
+can also add any other kind of value to a ``String`` with ``+`` or ``+=`` and
+the other value will be converted to a ``String`` automatically. Objects are
+converted by calling their ``toString`` method which we'll talk about in section
+5.4.
+
+Remember, however, that ``String``\ s are immutable, just like ``int``\ s and
+``double``\ s. So when we add two ``String``\ s (or a ``String`` and another
+value converted to a ``String``) we get a new ``String`` without making any
+change to the values being added together just like when we add `1 + 2` the
+original `1` and `2` aren't changed. When we use ``+=`` we are making a new
+``String`` by adding something to the current value of a variable and then
+assigning that new value back into the variable, again just like with numbers.
.. activecode:: lcso1
:language: java
:autograde: unittest
:practice: T
-
- Try the following code. Add another variable for a lastname that is "Hernandez". Use += or + to add the lastname variable after name to the result. Use += or + to add 2 more exclamation points (!) to the end of the happy birthday greeting in result.
+
+ Try the following code. Add another variable for a lastname that is "Hernandez". Use += or + to add the lastname variable after name to the result. Use += or + to add 2 more exclamation points (!) to the end of the happy birthday greeting in result.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- String start = "Happy Birthday";
- String name = "Jose";
- String result = start + " " + name; // add together strings
- result += "!"; // add on to the same string
- System.out.println(result);
- }
+ public static void main(String[] args)
+ {
+ String start = "Happy Birthday";
+ String name = "Jose";
+ String result = start + " " + name; // add together strings
+ result += "!"; // add on to the same string
+ System.out.println(result);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Happy Birthday Jose Hernandez!!!";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
-
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Happy Birthday Jose Hernandez!!!";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCodeContains()
+ {
+ boolean ifCheck2 = checkCodeContains("new String variable lastname", "String lastname = ");
+ assertTrue(ifCheck2);
+ }
+ }
+
.. note::
Note that spaces are not added between strings automatically. If you want a space between two strings then add one using + " " +. If you forget to add spaces, you will get smushed output like "HiJose" instead of "Hi Jose". And remember that variables are never put inside the quotes ("") since this would print the variable name out letter by letter instead of its value.
@@ -269,167 +285,189 @@ Strings can be **appended** to each other to create a new string using the ``+``
String s1 = "xy";
String s2 = s1;
s1 = s1 + s2 + "z";
-
-.. index::
- single: toString
- pair: Object; toString
-You can even add other items to a string using the ``+`` operator. The other item will be converted to a string using the ``toString`` operator if it is an object and then appended to the current string. All objects inherit a ``toString`` method that returns a string representation of the object.
-
+.. index::
+ single: toString
+ pair: Object; toString
+
+You can even add other items to a string using the ``+`` operator. Primitive
+values like ``int`` and ``boolean`` will be converted to a ``String`` like what
+you would type into a Java program and objects will be converted to ``String`` using the
+``toString`` method discussed in the previous section. All objects inherit a
+``toString`` method that returns a ``String`` representation of the object and
+many classes **override** it to produce a useful human-readable value. (We'll
+talk about overriding in detail in Unit 9.)
+
|CodingEx| **Coding Exercise:**
.. activecode:: lcso2
:language: java
:autograde: unittest
-
+
What do you think the following will print? Guess before you hit run. If you want the addition to take place before the numbers are turned into a string what should you do? Try to modify the code so that it adds 4 + 3 before appending the value to the string. Hint: you used this to do addition before multiplication in arithmetic expressions.
~~~~
public class Test2
{
- public static void main(String[] args)
- {
- String message = "12" + 4 + 3;
- System.out.println(message);
- }
+ public static void main(String[] args)
+ {
+ String message = "12" + 4 + 3;
+ System.out.println(message);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "127";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
-
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "127";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testParen() throws IOException
+ {
+ String code = removeSpaces(getCodeWithoutComments());
+ String expect = "(4+3)";
+ boolean passed = code.contains(expect);
+
+ passed = getResults("" + true, "" + passed, "Checking code for added parentheses");
+ assertTrue(passed);
+ }
+ }
+
.. note::
- If you are appending a number to a string it will be converted to a string first before being appended.
-
+ If you are appending a number to a string it will be converted to a string first before being appended.
+
Since the same operators are processed from left to right this will print ``1243``. First 4 will be turned into a string and appended to 12 and then 3 will be turned into a string and appended to 124. If you want to do addition instead, try using parentheses!
-What if you wanted to print out a double quote " character? Since the double quote " is a special character with meaning in Java, we put in a backslash in front of the quote to signal that we want just the character. This is called a **backslash escape sequence**. And if you wanted to print out a backslash, you would have to backslash it too in order to escape its special meaning. Another useful backslashed character is backslash \\n which will put in a newline.
+What if you wanted to print out a double quote " character? Since the double quote " is a special character with meaning in Java, we put in a backslash in front of the quote to signal that we want just the character. This is called a **backslash escape sequence**. And if you wanted to print out a backslash, you would have to backslash it too in order to escape its special meaning. Another useful backslashed character is backslash \\n which will put in a newline.
.. activecode:: bhescape
:language: java
:autograde: unittest
-
+
Here are the escape sequences that may be used in the AP course.
~~~~
public class TestEscape
{
- public static void main(String[] args)
- {
- String message = "Here is a backslash quote \" " +
- " and a backslashed backslash (\\) " +
- "Backslash n \n prints out a new line.";
- System.out.println(message);
- }
+ public static void main(String[] args)
+ {
+ String message =
+ "Here is a backslash quote \" "
+ + " and a backslashed backslash (\\) "
+ + "Backslash n \n prints out a new line.";
+ System.out.println(message);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = output;
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = output;
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
|Groupwork| Programming Challenge : Mad Libs
--------------------------------------------
Have you ever played MAD LIBS? In this game, you first choose a bunch of words without looking at the story and then those words are filled into the story to make it sound very wacky! Fill in the variables below with Strings for each word, and then run to see the wacky story.
-.. |repl| raw:: html
- repl.it
-
+.. |JuiceMind| raw:: html
+
+ JuiceMind
+
.. |Scanner| raw:: html
Scanner class
-
-Then, working in pairs, come up with another silly story that uses at least 5 new String variables. When you're done, try another team's mad libs code. Your teacher may ask you to create this program in a Java IDE like |repl| so that you can use input to read in the words (see input examples using the |Scanner|).
+
+Then, working in pairs, come up with another silly story that uses at least 5 new String variables. When you're done, try another team's mad libs code. Your teacher may ask you to create this program in a Java IDE that can do input for example this coding exercise on |JuiceMind| using the |Scanner| to read in input into the variables.
.. activecode:: challenge2-6-MadLibs
:language: java
:autograde: unittest
:practice: T
-
- If you used repl.it for this challenge, copy the url of your repl here to turn in.
+
+ Replace the nulls below with silly words to create a silly poem. Run the code to see the poem. Then, create your own silly story using 5 more String variables.
~~~~
public class MadLibs1
{
- public static void main(String[] args)
- {
- // fill these in with silly words/strings (don't read the poem yet)
- String pluralnoun1 =
- String color1 =
- String color2 =
- String food =
- String pluralnoun2 =
-
-
- // Run to see the silly poem!
- System.out.println("Roses are " + color1);
- System.out.println(pluralnoun1 + " are " + color2);
- System.out.println("I like " + food);
- System.out.println("Do " + pluralnoun2 + " like them too?");
-
- // Now come up with your own silly poem!
-
- }
+ public static void main(String[] args)
+ {
+ // fill these in with silly words/strings (don't read the poem yet)
+ String pluralnoun1 = null;
+ String color1 = null;
+ String color2 = null;
+ String food = null;
+ String pluralnoun2 = null;
+
+
+ // Run to see the silly poem!
+ System.out.println("Roses are " + color1);
+ System.out.println(pluralnoun1 + " are " + color2);
+ System.out.println("I like " + food);
+ System.out.println("Do " + pluralnoun2 + " like them too?");
+
+ // Now come up with your own silly poem!
+ }
}
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Roses are *\n* are *\nI like *\nDo * like them too?";
-
- boolean passed = getResultsRegEx(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void testNull() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "null";
-
- String actual = countOccurences(output, expect) + " null values";
+ import org.junit.*;
- boolean passed = getResults("0 null values", actual, "No null values");
- assertTrue(passed);
- }
- }
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Roses are *\n* are *\nI like *\nDo * like them too?";
+
+ boolean passed = getResultsRegEx(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ @Test
+ public void testNull() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "null";
+ String actual = countOccurences(output, expect) + " null values";
+ boolean passed = getResults("0 null values", actual, "No null values");
+ assertTrue(passed);
+ }
+ }
Summary
-------------------
@@ -441,8 +479,8 @@ Summary
- **new** is used to create a new object of a class.
- **null** is used to indicate that an object reference doesn't refer to any object yet.
-- String objects can be concatenated using the + or += operator, resulting in a new String object.
+- String objects can be concatenated using the ``+`` or ``+=`` operator, resulting in a new String object.
- Primitive values can be concatenated with a String object. This causes implicit conversion of the values to String objects.
-- Escape sequences start with a backslash \\ and have special meaning in Java. Escape sequences used in this course include \", \\, and \\n to print out a quote, backslash, and a new line.
+- Escape sequences start with a backslash ``\`` and have special meaning in Java. Escape sequences used in this course include ``\"``, ``\\``, and ``\n`` to print out a quote, backslash, and a new line.
diff --git a/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst b/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst
index 38c2fb267..621cbd8ae 100644
--- a/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst
+++ b/_sources/Unit2-Using-Objects/topic-2-7-string-methods.rst
@@ -1,37 +1,24 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 2-7-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-.. |AP CS A Reference Sheet| raw:: html
- AP CS A Java Quick Reference Sheet
-
-String Methods
+.. |AP CSA Reference Sheet| raw:: html
+
+ AP CSA Java Quick Reference Sheet
+
+|Time90|
+
+String Methods
=================
-.. index::
- pair: String; length
- pair: String; substring
- pair: String; indexOf
- pair: String; compareTo
- pair: String; equals
+.. index::
+ pair: String; length
+ pair: String; substring
+ pair: String; indexOf
+ pair: String; compareTo
+ pair: String; equals
pair: String; methods
A string holds characters in a sequence. Each character is at a position or **index** which starts with 0 as shown below. An **index** is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14.
@@ -46,72 +33,78 @@ A string holds characters in a sequence. Each character is at a position or **i
.. note::
- The first character in a string is at index 0 and the last characters is at **length** - 1.
+ The first character in a string is at index 0 and the last characters is at **length** -1.
-For the AP CS A exam, you only need to know how to use the following String methods. All of the String method descriptions are included in the |AP CS A Reference Sheet| that you get during the exam so you don't have to memorize these.
+For the AP CSA exam, you only need to know how to use the following String methods. All of the String method descriptions are included in the |AP CSA Reference Sheet| that you get during the exam so you don't have to memorize these.
- **int length()** method returns the number of characters in the string, including spaces and special characters like punctuation.
- **String substring(int from, int to)** method returns a new string with the characters in the current string starting with the character at the ``from`` index and ending at the character *before* the ``to`` index (if the ``to`` index is specified, and if not specified it will contain the rest of the string).
- - **int indexOf(String str)** method returns the index of the beginning of ``str`` in the current string or -1 if it isn't found.
+ - **int indexOf(String str)** method searches for the string ``str`` in the current string and returns the index of the beginning of ``str`` in the current string or -1 if it isn't found.
- **int compareTo(String other)** returns a negative value if the current string is less than the ``other`` string alphabetically, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the ``other`` string alphabetically.
- - **boolean equals(String other)** returns true when the characters in the current string are the same as the ones in the ``other`` string. This method is inherited from the Object class, but is **overriden** which means that the String class has its own version of that method.
+ - **boolean equals(String other)** returns true when the characters in the current string are the same as the ones in the ``other`` string. This method is inherited from the Object class, but is **overridden** which means that the String class has its own version of that method.
String Methods: length, substring, indexOf
------------------------------------------
-Run the code below to see the output from the String methods ``length``, ``substring``, and ``indexOf``. The length method returns the number of characters in the string, not the last index which is length-1. The ``str.substring(from,to)`` method returns the substring from the ``from`` index up to (but not including) the ``to`` index. The method ``str.indexOf(substring)`` returns the index of where it finds substring in str or -1 if it is not there.
+Run the code below to see the output from the String methods ``length``, ``substring``, and ``indexOf``. The length method returns the number of characters in the string, not the last index which is length -1. The ``str.substring(from,to)`` method returns the substring from the ``from`` index up to (but not including) the ``to`` index. The method ``str.indexOf(substring)`` searches for the substring in str and returns the index of where it finds substring in str or -1 if it is not there.
.. activecode:: lcsm1
:language: java
:autograde: unittest
- This code shows the output from String methods length, substring, and indexOf. How many letters does substring(0,3) return? What does indexOf return when its argument is not found?
+ This code shows the output from String methods length, substring, and indexOf. How many letters does substring(0,3) return? What does indexOf return when its argument is not found?
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- String message1 = "This is a test";
- String message2 = "Hello Class";
-
- System.out.println(message1.length());
- System.out.println(message2.length());
-
- System.out.println(message1.substring(0,3));
- System.out.println(message2.substring(4,5));
- System.out.println(message1.substring(5));
-
- System.out.println(message1.indexOf("is")); // This will match the is in "This"!
- System.out.println(message1.indexOf("Hello"));
- System.out.println(message2.indexOf("Hello"));
-
- // lowercase and uppercase are not on the AP exam, but still useful
- System.out.println(message2.toLowerCase());
- System.out.println(message2.toUpperCase());
- }
+ public static void main(String[] args)
+ {
+ String message1 = "This is a test";
+ String message2 = "Hello Class";
+
+ System.out.println(message1.length());
+ System.out.println(message2.length());
+
+ System.out.println(message1.substring(0, 3));
+ System.out.println(message1.substring(2, 3));
+ System.out.println(message1.substring(5));
+
+ System.out.println(
+ message1.indexOf("is")); // This will match the is in "This"!
+ System.out.println(message1.indexOf("Hello"));
+ System.out.println(message2.indexOf("Hello"));
+
+ // lowercase and uppercase are not on the AP exam, but still useful
+ System.out.println(message2.toLowerCase());
+ System.out.println(message2.toUpperCase());
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "14\n11\nThi\no\nis a test\n2\n-1\n0\nhello class\nHELLO CLASS";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main").trim();
+ String expect = "14\n11\nThi\ni\nis a test\n2\n-1\n0\nhello class\nHELLO CLASS";
+ boolean passed = output.contains(expect);
+
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+ }
.. note::
@@ -167,7 +160,7 @@ Run the code below to see the output from the String methods ``length``, ``subst
:feedback_a: This would be true if substring returned all the characters from the first index to the last inclusive, but it does not include the character at the last index.
:feedback_b: This would be true if it was s1.substring(0,1)
:feedback_c: This would be true if it was s1.substring(0,2)
- :feedback_d: Substring returns all the characters from the starting index to the last index - 1.
+ :feedback_d: Substring returns all the characters from the starting index to the last index -1.
What is the value of s2 after the following code executes?
@@ -176,23 +169,6 @@ Run the code below to see the output from the String methods ``length``, ``subst
String s1 = "baby";
String s2 = s1.substring(0,3);
-.. .. mchoice:: qsb_4
- :practice: T
- :answer_a: 7
- :answer_b: 8
- :answer_c: 9
- :correct: c
- :feedback_a: Count spaces and punctuation in the length.
- :feedback_b: Did you forget to count a space or punctuation?
- :feedback_c: The length method returns the number of characters including spaces and punctuation.
-
- What is the value of len after the following executes?
-
- .. code-block:: java
-
- String s1 = "Miss you!";
- int len = s1.length();
-
.. mchoice:: qsb_4b
:practice: T
:answer_a: by
@@ -219,9 +195,9 @@ Run the code below to see the output from the String methods ``length``, ``subst
CompareTo and Equals
-----------------------
-We can compare primitive types like int and double using operators like == and < or >, which you will learn about in the next unit. However, with reference types like String, you must use the methods equals and compareTo, not == or < or >.
+We can compare primitive types like int and double using operators like ``==`` and ``<`` or ``>``, which you will learn about in the next unit. However, with reference types like String, you must use the methods ``equals`` and ``compareTo``, not ``==`` or ``<`` or ``>``.
-The method ``compareTo`` compares two strings character by character. If they are equal, it returns 0. If the first string is alphabetically ordered before the second string (which is the argument of compareTo), it returns a negative number. And if the first string is alphabetically ordered after the second string, it returns a positive number. (The actual number that it returns does not matter, but it is the distance in the first letter that is different, e.g. A is 7 letters away from H.)
+The method ``compareTo`` compares two strings character by character. If they are equal, it returns 0. If the first string is alphabetically ordered before the second string (which is the argument of ``compareTo``), it returns a negative number. And if the first string is alphabetically ordered after the second string, it returns a positive number. (The actual number that it returns does not matter, but it is the distance in the first letter that is different, e.g. A is 7 letters away from H.)
.. figure:: Figures/compareTo.png
:width: 350px
@@ -231,58 +207,57 @@ The method ``compareTo`` compares two strings character by character. If they ar
Figure 2: compareTo returns a negative or positive value or 0 based on alphabetical order
-The equals method compares the two strings character by character and returns true or false. Both compareTo and equals are case-sensitive. There are case-insensitive versions of these methods, ``compareToIgnoreCase`` and ``equalsIgnoreCase``, which are not on the AP exam.
+The ``equals`` method compares the two strings character by character and returns ``true`` or ``false``. Both ``compareTo`` and ``equals`` are case-sensitive. There are case-insensitive versions of these methods, ``compareToIgnoreCase`` and ``equalsIgnoreCase``, which are not on the AP exam.
-Run the example below to see the output from ``compareTo`` and ``equals``. Since "Hello!" would be alphabetically ordered after "And", compareTo returns a positive number. Since "Hello!" would be alphabetically ordered before "Zoo", compareTo returns a negative number. Notice that equals is case-sensitive.
+Run the example below to see the output from ``compareTo`` and ``equals``. Since ``"Hello!"`` would be alphabetically ordered after ``"And"``, ``compareTo`` returns a positive number. Since ``"Hello!"`` would be alphabetically ordered before ``"Zoo"``, ``compareTo`` returns a negative number. Notice that ``equals`` is case-sensitive.
.. activecode:: lcsm2
:language: java
:autograde: unittest
- Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number?
+ Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number?
~~~~
public class Test2
{
- public static void main(String[] args)
- {
- String message = "Hello!";
+ public static void main(String[] args)
+ {
+ String message = "Hello!";
- System.out.println(message.compareTo("Hello there"));
- System.out.println(message.compareTo("Hello!"));
- System.out.println(message.compareTo("And"));
- System.out.println(message.compareTo("Zoo"));
+ System.out.println(message.compareTo("Hello!"));
+ System.out.println(message.compareTo("And"));
+ System.out.println(message.compareTo("Zoo"));
- System.out.println(message.equals("Hello!"));
- System.out.println(message.equals("hello!"));
- }
+ System.out.println(message.equals("Hello!"));
+ System.out.println(message.equals("hello!"));
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "1\n0\n7\n-18\ntrue\nfalse";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "0\n7\n-18\ntrue\nfalse";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
.. |String class| raw:: html
String class
-
-There are lots of other methods in the String class. You can look through the Java documentation for the |String class| online. You don't have to know all of these for the exam, but you can use them if you want to on the exam.
-The String library which is built into the default java.lang library simplifies a lot of complex programming tasks for us. Classes are grouped together into a **package** like java.lang. Many other useful library packages can be imported in. Programmers provide **Application Program Interfaces (APIs)** to allow other programmers to use their code. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class.
+There are lots of other methods in the String class. You can look through the Java documentation for the |String class| online. You don't have to know all of these for the exam, but you can use them if you want to on the exam.
+An **Application Programming Interface (API)** is a library of prewritten classes that simplify complex programming tasks for us. These classes are grouped together in a **package** like java.lang and we can import these packages (or individual classes) into our programs to make use of them. For instance, we have just discussed the String library built into the default java.lang package - it takes care of the detailed work of manipulating strings for us. There are many other useful library packages as well, both in the java.lang package and in other packages. Documentation for APIs and libraries are essential to understanding how to use these classes.
.. note::
@@ -292,20 +267,20 @@ The String library which is built into the default java.lang library simplifies
.. dragndrop:: ch4_str1
:feedback: Review the vocabulary.
- :match_1: the position of a character in a string|||index
+ :match_1: the position of a character in a string|||index
:match_2: a new string that is a part of another string with 0 to all characters copied from the original string|||substring
:match_3: doesn't change|||immutable
:match_4: the number of characters in a string|||length
-
+
Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct
-
+
.. dragndrop:: ch4_str2
:feedback: Review the vocabulary.
:match_1: Returns true if the characters in two strings are the same|||equals
:match_2: Returns the position of one string in another or -1|||indexOf
:match_3: Returns a number to indicate if one string is less than, equal to, or greater than another|||compareTo
:match_4: Returns a string representing the object that is passed to this method|||toString
-
+
Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct.
.. mchoice:: qsb_5
@@ -385,9 +360,9 @@ The String library which is built into the default java.lang library simplifies
String s1 = "Hi";
String s2 = "Bye";
int answer = s1.compareTo(s2);
-
-
+
+
Common Mistakes with Strings
@@ -399,57 +374,64 @@ The following code shows some common mistakes with strings.
:language: java
:practice: T
:autograde: unittest
-
+
This code contains some common mistakes with strings. Fix the code to use the string methods correctly.
~~~~
public class StringMistakes
{
- public static void main(String[] args)
- {
- String str1 = "Hello!";
-
- // Print out the first letter?
- System.out.println("The first letter in " + str1 + ":" + str1.substring(1,1) );
-
- // Print out the last character?
- System.out.println("The last char. in " + str1 + ":" + str1.substring(8) );
-
- // Print str1 in lower case? Will str1 change?
- str1.toLowerCase();
- System.out.println("In lowercase: " + str1);
-
- }
+ public static void main(String[] args)
+ {
+ String str1 = "Hello!";
+
+ // Print out the first letter?
+ System.out.println(
+ "The first letter in " + str1 + ":" + str1.substring(1, 1));
+
+ // Print out the last character?
+ System.out.println(
+ "The last char. in " + str1 + ":" + str1.substring(8));
+
+ // Print str1 in lower case? Will str1 change?
+ str1.toLowerCase();
+ System.out.println("In lowercase: " + str1);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "The first letter in Hello!:H\nThe last char. in Hello!:!\nIn lowercase: hello!";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main").trim();
+ String expect =
+ "The first letter in Hello!:H\nThe last char. in Hello!:!\nIn lowercase: hello!";
+ boolean passed = output.contains(expect);
+
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+ }
Here is a list of common mistakes made with Strings.
-
-
- - Thinking that substrings include the character at the last index when they don't.
-
- - Thinking that strings can change when they can't. They are immutable.
-
- - Trying to access part of a string that is not between index 0 and length - 1. This will throw an IndexOutOfBoundsException.
-
+
+
+ - Thinking that substrings include the character at the last index when they don't.
+
+ - Thinking that strings can change when they can't. They are immutable.
+
+ - Trying to access part of a string that is not between index 0 and length -1. This will throw an IndexOutOfBoundsException.
+
- Trying to call a method like ``indexOf`` on a string reference that is null. You will get a null pointer exception.
-
- - Using ``==`` to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use ``equals`` or ``compareTo`` instead.
- - Treating upper and lower case characters the same in Java. If ``s1 = "Hi"`` and ``s2 = "hi"`` then ``s1.equals(s2)`` is false.
+
+ - Using ``==`` to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use ``equals`` or ``compareTo`` instead.
+ - Treating upper and lower case characters the same in Java. If ``s1 = "Hi"`` and ``s2 = "hi"`` then ``s1.equals(s2)`` is false.
|Groupwork| Programming Challenge : Pig Latin
@@ -459,104 +441,128 @@ Here is a list of common mistakes made with Strings.
:width: 100
:align: middle
:alt: pig latin
-
-|pig| Can you speak Pig Latin? In Pig Latin, you take the first letter and put it at the end of the word and add the letters "ay" to the end. For example, "pig" becomes "igpay".
+
+|pig| Can you speak Pig Latin? In Pig Latin, you take the first letter and put it at the end of the word and add the letters "ay" to the end. For example, "pig" becomes "igpay".
Create a program that takes a word and transforms it to Pig Latin using String methods. You may need the word's length, a substring that does not include the first letter, and a substring that is just the first letter (you can get the ith letter of a string using substring(i,i+1) so for example the letter at index 3 would be substring(3,4)).
-.. |repl| raw:: html
- repl.it
-
+.. |JuiceMind| raw:: html
+
+ JuiceMind
.. |Scanner| raw:: html
Scanner class
-
-Your teacher may ask you to create this program in a Java IDE like |repl| so that you can use input to read in the word (see input examples using the |Scanner|).
+
+Your teacher may ask you to create this program in a Java IDE that can use input to read in the word, for example in |JuiceMind| using the |Scanner|.
.. activecode:: challenge2-7-PigLatin
:language: java
:practice: T
:autograde: unittest
-
+
Use the substring method to transform a word into Pig Latin where the first letter is put at the end and "ay" is added. The word pig is igpay in Pig Latin.
~~~~
public class PigLatin
{
public static void main(String[] args)
{
- String word =
- // Use word.substring to construct word in pig latin
- String pigLatin =
-
- System.out.println(word + " in Pig Latin is " + pigLatin);
+ String word = "pig";
+
+ // Change this to use word.substring to construct the pig latin
+ // version of word. It should work even if you change the value of
+ // word above.
+ String pigLatin = "";
+
+
+ System.out.println(word + " in Pig Latin is " + pigLatin);
}
}
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "* in Pig Latin is *ay";
- boolean passed = getResultsRegEx(expect, output, "Expected output from main");
- assertTrue(passed);
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "* in Pig Latin is *ay";
+ boolean passed = getResultsRegEx(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
@Test
- public void testContainsSubstring()
+ public void testContainsSubstring()
{
String target = "word.substring(";
int count = countOccurences(getCode(), target);
boolean passed = count >= 2;
- passed = getResults("2 substring calls", count + " substring call(s)","Code contains calls to substring method", passed);
+ passed =
+ getResults(
+ "2 substring calls",
+ count + " substring call(s)",
+ "Code contains calls to substring method",
+ passed);
assertTrue(passed);
}
- }
-
-
-
+ }
Summary
-------------------
-- **index** - A number that represents the position of a character in a string. The first character in a string is at index 0.
-- **length** - The number of characters in a string.
+- **index** - A number that represents the position of a character in a string. The first character in a string is at index 0.
+- **length** - The number of characters in a string.
- **substring** - A new string that contains a copy of part of the original string.
- A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.
-- String objects are **immutable**, meaning that String methods do not change the String object. Any method that seems to change a string actually creates a new string.
+- String objects are **immutable**, meaning that String methods do not change the String object. Any method that seems to change a string actually creates a new string.
-- The following String methods and constructors, including what they do and when they are used, are part of the |AP CS A Reference Sheet| that you can use during the exam:
+- The following String methods and constructors, including what they do and when they are used, are part of the |AP CSA Reference Sheet| that you can use during the exam:
- **String(String str)** : Constructs a new String object that represents the same sequence of characters as str.
-
- - **int length()** : returns the number of characters in a String object.
- - **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to – 1).
+ - **int length()** : returns the number of characters in a String object.
+
+ - **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to -1).
- **String substring(int from)** : returns substring(from, length()).
-
- - **int indexOf(String str)** : returns the index of the first occurrence of str; returns -1 if not found.
-
+
+ - **int indexOf(String str)** : searches for str in the current string and returns the index of the first occurrence of str; returns -1 if not found.
+
- **boolean equals(String other)** : returns true if this (the calling object) is equal to other; returns false otherwise.
-
+
- **int compareTo(String other)** : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other.
-- ``str.substring(index, index + 1)`` returns a single character at index in string str.
+- ``str.substring(index, index + 1)`` returns a single character at index in string str.
+
+
+String Methods Game
+---------------------------
+
+.. |game| raw:: html
+
+ game
+
+
+Try the game below written by AP CSA teacher Chandan Sarkar. Click on **Strings** and then on the letters that would be the result of the string method calls. We encourage you to work in pairs and see how high a score you can get.
+.. raw:: html
+
+
-.. index::
+
+.. index::
single: append
single:concatenate
single: immutable
@@ -566,10 +572,4 @@ Summary
single: substring
single: string
single: reference
- single: object reference
-
-
-
-
-
-
+ single: object reference
diff --git a/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst b/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst
index 281c9b6bb..da461d218 100644
--- a/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst
+++ b/_sources/Unit2-Using-Objects/topic-2-8-IntegerDouble.rst
@@ -1,100 +1,91 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 2-8-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
+
+|Time45|
Wrapper Classes - Integer and Double
====================================
-.. index::
- pair: integer; minimum
- pair: integer; maximum
+.. index::
+ pair: integer; minimum
+ pair: integer; maximum
+
+For every primitive type in Java, there is a built-in object type called a wrapper class. The wrapper class for int is called Integer, and for double it is called Double. Sometimes you may need to create a wrapped object for a primitive type so that you can give it to a method that is expecting an object. To wrap a value, call the constructor for the wrapper class in earlier versions of Java. In Java 9 on, this is **deprecated** which means it's not the best way to do this anymore, and you should instead just set it equal to a value. The AP CSA Exam covers Java 7 which does allow using the constructor.
-For every primitive type in Java, there is a built-in object type called a wrapper class. The wrapper class for int is called Integer, and for double it is called Double. Sometimes you may need to create a wrapped object for a primitive type so that you can give it to a method that is expecting an object. To wrap a value, call the constructor for the wrapper class in earlier versions of Java. In Java 9 on, this is **deprecated** which means it's not the best way to do this anymore, and you should instead just set it equal to a value. The AP CS A Exam covers Java 7 which does allow using the constructor.
+.. code-block:: java
-.. code-block:: java
-
// in older versions of Java (and on the AP exam)
Integer i = new Integer(2); // create an object with 2 in it
- Double d = new Double(3.5); // create an object with 3.5 in it
+ Double d = new Double(3.5); // create an object with 3.5 in it
// in newer versions of Java (9+)
Integer i = 2;
Double d = 3.5;
-
-
+
+
These wrapper classes (defined in the java.lang package) are also useful because they have some special values (like the minimum and maximum values for the type) and methods that you can use. Try the following code to see the minimum and maximum values possible for the type int.
-
+
.. activecode:: lcmm1
:language: java
:autograde: unittest
-
+
What's the minimum and maximum numbers for an int? What happens if you go beyond these limits with - 1 or + 1?
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- System.out.println(Integer.MIN_VALUE);
- System.out.println(Integer.MAX_VALUE);
- System.out.println(Integer.MIN_VALUE - 1);
- System.out.println(Integer.MAX_VALUE + 1);
- }
+ public static void main(String[] args)
+ {
+ System.out.println(Integer.MIN_VALUE);
+ System.out.println(Integer.MAX_VALUE);
+ System.out.println(Integer.MIN_VALUE - 1);
+ System.out.println(Integer.MAX_VALUE + 1);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "-2147483648\n2147483647\n2147483647\n-2147483648";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
-The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space. In 32 bits of space with one bit used to represent the sign you can represent that many values. Why is there one more negative number than positive number? It is because 0 is considered a positive number.
-
-.. index::
- single: overflow
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "-2147483648\n2147483647\n2147483647\n-2147483648";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
+The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space. In 32 bits of space with one bit used to represent the sign you can represent that many values. Why is there one more negative number than positive number? It is because 0 is considered a positive number.
+
+.. index::
+ single: overflow
What do the last two lines print out? Did this surprise you? Java will actually return the maximum integer value if you try to subtract one from the minimum value. This is called **underflow**. And, Java will return the minimum integer value if you try to add one to the maximum. This is called **overflow**. It is similar to how odometers work -- in a really old car that reaches the maximum miles possible on the odometer, the odometer rolls over back to 0, the minimum value. In Java, any int value that surpasses 32 bits gets rolled over, so that the Integer.MAX_VALUE 2147483647 incremented (+1) returns -2147483648 which is the Integer.MIN_VALUE.
-When would you ever use Integer.MIN_VALUE or Integer.MAX_VALUE? They are handy if you want to initialize a variable to the smallest possible value and then search a sequence of values for a larger value.
-
+When would you ever use Integer.MIN_VALUE or Integer.MAX_VALUE? They are handy if you want to initialize a variable to the smallest possible value and then search a sequence of values for a larger value.
+
**Autoboxing** is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is passed as a parameter to a method that expects an object of the corresponding wrapper class or assigned to a variable of the corresponding wrapper class. Here's an example of autoboxing.
-.. code-block:: java
-
+.. code-block:: java
+
Integer i = 2;
Double d = 3.5;
**Unboxing** is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is passed as a parameter to a method that expects a value of the corresponding primitive type or assigned to a variable of the corresponding primitive type. Here's an example of unboxing:
-.. code-block:: java
-
+.. code-block:: java
+
Integer i = 2; // autoboxing - wrap 2
int number = i; // unboxing - back to primitive type
@@ -109,7 +100,7 @@ When would you ever use Integer.MIN_VALUE or Integer.MAX_VALUE? They are handy
:match_4: int|||primitive type
:match_5: Integer.MAX_VALUE + 1|||overflow
:match_6: Integer.MIN_VALUE - 1 |||underflow
-
+
Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct.
Here are some more useful methods in the Integer and Double classes:
@@ -117,43 +108,57 @@ Here are some more useful methods in the Integer and Double classes:
.. activecode:: integerMethods
:language: java
:autograde: unittest
-
+
Run the code below to see useful methods in the Integer and Double wrapper classes.
- ~~~~
+ ~~~~
public class Test2
{
- public static void main(String[] args)
- {
- Integer i = 2;
- Double d = 3.5;
- System.out.println( i.intValue() ); // intValue() returns the primitive value
- System.out.println( d.doubleValue() );
-
- String ageStr = "16";
- // Integer.parseInt and Double.parseDouble are often used to
- // convert an input string to a number so you can do math on it.
- // They are not on the AP exam
- System.out.println("Age " + ageStr + " in 10 years is " + (Integer.parseInt(ageStr) + 10) );
- System.out.println("Note that + with strings does concatenation, not addition: " + (ageStr + 10));
- }
+ public static void main(String[] args)
+ {
+ Integer i = 2;
+ Double d = 3.5;
+ System.out.println(
+ i.intValue()); // intValue() returns the primitive value
+ System.out.println(d.doubleValue());
+
+ String ageStr = "16";
+ // Integer.parseInt and Double.parseDouble are often used to
+ // convert an input string to a number so you can do math on it.
+ // They are not on the AP exam
+ System.out.println(
+ "Age "
+ + ageStr
+ + " in 10 years is "
+ + (Integer.parseInt(ageStr) + 10));
+ System.out.println(
+ "Note that + with strings does concatenation, not addition: "
+ + (ageStr + 10));
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "2\n3.5\nAge 16 in 10 years is 26\nNote that + with strings does concatenation, not addition: 1610";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "2\n"
+ + "3.5\n"
+ + "Age 16 in 10 years is 26\n"
+ + "Note that + with strings does concatenation, not addition: 1610";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
|Groupwork| Programming Challenge : Debugging
----------------------------------------------
@@ -162,47 +167,48 @@ Can you find and fix all the bugs in the following code to use the correct Integ
.. activecode:: challenge2-8-wrapperDebug
:language: java
:autograde: unittest
-
+
Find and fix the bugs below to use the correct Integer and Double methods and variables.
~~~~
public class Debug
{
- public static void main(String[] args)
- {
- integer i = 2.3;
- Double d = 5;
- System.out.println( i.intValue );
- System.out.println( doubleValue() );
- // Print out the min and max values possible for integers
- System.out.println(Integer.min_value);
- System.out.println( i.MAX_VALUE() );
- }
+ public static void main(String[] args)
+ {
+ integer i = 2.3;
+ Double d = 5;
+ System.out.println( i.intValue );
+ System.out.println( doubleValue() );
+ // Print out the min and max values possible for integers
+ System.out.println(Integer.min_value);
+ System.out.println( int.MAX_VALUE() );
+ }
}
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "2\n5.0\n-2147483648\n2147483647";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void testCode() throws IOException
- {
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "2\n5.0\n-2147483648\n2147483647";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCode() throws IOException
+ {
String target = "Integer.MAX_VALUE";
boolean passed = checkCodeContains("MAX_VALUE", target);
assertTrue(passed);
- }
- }
-
-
+ }
+ }
Summary
-------------------
@@ -235,5 +241,3 @@ Summary
- Passed as a parameter to a method that expects a value of the corresponding primitive type.
- Assigned to a variable of the corresponding primitive type.
-
-
diff --git a/_sources/Unit2-Using-Objects/topic-2-9-Math.rst b/_sources/Unit2-Using-Objects/topic-2-9-Math.rst
index 924027af8..fde43eda1 100644
--- a/_sources/Unit2-Using-Objects/topic-2-9-Math.rst
+++ b/_sources/Unit2-Using-Objects/topic-2-9-Math.rst
@@ -1,84 +1,400 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 2-9-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
+
+|Time90|
Using the Math Class
====================
-.. index::
+.. index::
single: Math methods
- single: random method
- pair: Math; random method
+ single: random method
+ pair: Math; random method
+
+Games would be boring if the same thing happened each time you played the game. Random numbers can be used in games to generate different outcomes each time the game is played. In Java, the ``Math.random()`` method to is used to generate a random number.
+
+There are lots of mathematical methods in the ``Math`` class
+that you might want to use in your programs, like ``Math.pow(2,3)`` which calculates the 2 to the power of 3 which is 8.
-Games would be boring if the same thing happened each time you played the game. Games often use random numbers
-to generate different possibilities. You need to know how to use the ``Math.random()`` method to generate a random number.
+These methods are in the **Math** class defined in the java.lang package. These are **static methods** which means you can call them by just using ``ClassName.methodName()`` without creating an object.
+This is why we can just say Math.random() instead of having to define an object of the class Math.
-There are lots of mathematical methods
-that you might want to use in your programs like ``Math.abs`` (absolute value). These methods are in the **Math** class defined in the java.lang package. These are **static methods** which means you can call them by just using ``ClassName.methodName()`` without creating an object or just the method name if they are called from within the same class.
.. note::
- **Static methods** (also called class methods) are called using the class name and the dot operator (.) followed by the method name, for example Math.random(). You do not need to create an object of the class to use them.
+ **Static methods** (also called class methods) are called using the class name and the dot operator (.) followed by the method name. You do not need to create an object of the class to use them. You can use ClassName.methodName() or just methodName() if they are called from within the same class.
+
+Mathematical Functions
+-----------------------
+
+.. |AP CSA Reference Sheet| raw:: html
+
+ AP CSA Java Quick Reference Sheet
+
+.. |Math class Javadocs| raw:: html
+
+ Math class Javadocs
+
+
+
+The ``Math`` class contains the following methods that are in the AP CSA subset. There are more ``Math`` methods, outside of what you need on the AP exam, that you can find in the |Math class Javadocs|.
+
+- ``int abs(int)`` : Returns the absolute value of an int value (which is the value of a number without its sign, for example ``Math.abs(-4)`` = 4).
+
+- ``double abs(double)`` : Returns the absolute value of a double value.
+
+- ``double pow(double, double)`` : Returns the value of the first parameter raised to the power of the second parameter.
+
+- ``double sqrt(double)`` : Returns the positive square root of a double value.
+
+- ``double random()`` : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!).
+
+
+.. note::
+
+ All the ``Math`` methods that you may need to use or understand on the AP
+ exam are listed in the |AP CSA Reference Sheet| that you can use during the
+ exam.
+
+These Math methods are mathematical functions that compute new values from their arguments. You may be able to guess what ``abs``, ``pow``, and ``sqrt`` do, from their abbreviations.
+
+``Math.abs`` takes a single argument, either a ``double`` or an
+``int`` and returns a value of the same type which is the absolute value of the
+argument. The absolute value is the positive value of the number without its sign or its distance from 0. So:
+
+.. code-block:: java
+
+ Math.abs(45); // returns 45
+ Math.abs(-45); // returns 45
+ Math.abs(33.3); // returns 33.3
+ Math.abs(-33.3); // returns 33.3
+
+.. image:: Figures/pow.png
+ :width: 80px
+ :align: left
+ :alt: Pow!
+
+
+``Math.pow`` takes two argument, both ``double``\ s and returns
+a ``double`` which is the first argument raised to the power of the second
+argument.
+
+.. code-block:: java
+
+ Math.pow(2 , 3); // returns 8.0
+ Math.pow(10, 6); // returns 1000000.0
+ Math.pow(2, -3); // returns 0.125
+
+``Math.sqrt`` takes an ``double`` argument and returns a positive ``double`` value which is the square root of the argument. For example, the square root of 9 is 3 because 3 squared is 9.
+
+.. code-block:: java
+
+ Math.sqrt(9); // returns 3.0
+
+Since these methods calculate and return a value, you need to use that value, for example in an assignment statement or in a print statement to see the result. For example:
+
+.. code-block:: java
-The ``Math.random()`` method returns a number greater than or equal to 0.0, and less than 1.0.
+ System.out.println("The square root of 9 is " + Math.sqrt(9));
+
+|CodingEx| **Coding Exercise**
+
+.. activecode:: trymath
+ :language: java
+ :autograde: unittest
+
+ Try the Math methods below. Change the code so that it computes the absolute value of -4, the square root of 9, and 3 raised to the power of 2.
+ ~~~~
+ public class TryMath
+ {
+ public static void main(String[] args)
+ {
+ // TODO: Change the code below to compute
+ // the absolute value of -4,
+ // the square root of 9,
+ // and 3 raised to the power of 2.
+ System.out.println( Math.abs(-2) );
+ System.out.println( Math.sqrt(4) );
+ System.out.println( Math.pow(2, 3) );
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "4\n3.0\n9.0\n";
+ boolean passed = getResults(expect, output, "Expected output from main after changing code");
+ assertTrue(passed);
+ }
+ }
+
+|Exercise| **Check Your Understanding**
+
+.. mchoice:: call-sqrt-mc
+
+ Knowing that ``Math.sqrt`` takes a single argument, Which of these are
+ syntactically correct method calls to ``sqrt``?
+
+ - ``Math.sqrt(2)``
+
+ + ✅ This is a simple call to ``Math.sqrt`` with the argument 2.
+
+ - ``Math.sqrt()``
+
+ - ❌ ``Math.sqrt`` takes one argument. This would be a correct call if it took no arguments.
+
+ - ``Math.sqrt(2, 4)``
+
+ - ❌ ``Math.sqrt`` takes one argument. This would be a correct call if it took two arguments.
+
+ - ``Math.sqrt(2 + 3)``
+
+ + ✅ The argument passed to ``Math.sqrt`` is the value of the expression 2 + 3, namely 5.
+
+ - ``Math.sqrt 2``
+
+ - ❌ You must have parentheses around the arguments.
+
+ - ``Math.sqrt(Math.sqrt(2))``
+
+ + ✅ The argument passed to ``Math.sqrt`` is the value of *another* call to
+ ``Math.sqrt`` which is perfectly fine.
+
+
+
+.. mchoice:: distance-mc
+ :multiple_answers:
+ :random:
+
+ The distance between two numbers on the number line is defined as the absolute value of their
+ difference. Their difference is just what you get when you subtract one from
+ the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.
+
+ .. image:: Figures/number-line.svg
+ :width: 450px
+ :align: center
+ :alt: number line
+
+ Which of the following are correct expressions to compute the
+ distance between the numbers ``a`` and ``b``.
+
+ - ``Math.abs(a - b)``
+
+ + ✅ ``a - b`` gives us the difference and ``Math.abs`` gives us the
+ absolute value of that difference.
+
+ - ``Math.abs(a) - Math.abs(b)``
+
+ - ❌ Consider the distance between -2 and 3. It should be five. What value
+ would this expression produce in that case?
+
+ - ``Math.abs(a + b)``
+
+ - ❌ We need to start with the difference between ``a`` and ``b``, not their sum.
+
+
+|CodingEx| **Coding Exercise**
+
+.. activecode:: distance-abs
+ :language: java
+ :autograde: unittest
+
+ The distance between two numbers on a number line, as we discussed in the problem
+ above, is defined as the absolute value of their difference.
+ Their difference is just what you get when you subtract one from the other.
+ For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.
+
+ Fill in the method ``distance`` below so it correctly computes the distance between two numbers ``a`` and ``b`` using subtraction and Math.abs.
+ ~~~~
+ public class DistanceCalculator
+ {
+
+ public static double distance(double a, double b)
+ {
+ // TODO: calculate the distance from a to b using subtraction and Math.abs.
+ double distance = 0.0;
+
+ return distance;
+ }
+
+ public static void main(String[] argv)
+ {
+ System.out.println("distance(13.5, 26.2) = " + distance(13.5, 26.2));
+ System.out.println("distance(26.2, 13.5) = " + distance(26.2, 13.5));
+ System.out.println(distance(13.5, 26.2) == distance(13.5, 26.2));
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void test1()
+ {
+ Object[] args = {10.5, 20.6};
+ String output = getMethodOutput("distance", args);
+ String expect = "10.1";
+ boolean passed = getResults(expect, output, "distance(10.5, 20.6)");
+ assertTrue(passed);
+ }
+ @Test
+ public void test2()
+ {
+ Object[] args = { -5.0, 2.4 };
+ String output = getMethodOutput("distance", args);
+ String expect = "7.4";
+ boolean passed = getResults(expect, output, "distance(-5.0, 2.4)");
+ assertTrue(passed);
+ }
+ }
+
+Random Numbers
+----------------
+
+.. image:: Figures/dice.png
+ :width: 100px
+ :align: left
+ :alt: Dice
+
+The ``Math.random()`` method returns a double number greater than or equal to 0.0, and less than 1.0.
+When we talk about ranges of numbers sometimes
+we need to be precise about whether the ends of the range are part of the range.
+For example, ``Math.random`` returns a number between 0 and 1, but does that
+mean it can return exactly 0? Or exactly 1? As it turns out it can return 0 but
+never returns 1.
+
+When we need to be precise about this we’d say that it returns a number between
+0, *inclusive*, and 1, *exclusive*, meaning *include* 0 but *exclude* 1. Lots of
+ranges in Java are expressed this way, as you’ll see later on with an inclusive
+bottom and exclusive top.
.. activecode:: random1
:language: java
:autograde: unittest
- Try out the following code. Run it several times to see what it prints each time.
+ Try the following code. Run it several times to see what it prints each time.
~~~~
public class Test3
{
- public static void main(String[] args)
- {
- System.out.println(Math.random());
- System.out.println(Math.random());
- }
+ public static void main(String[] args)
+ {
+ System.out.println(Math.random());
+ System.out.println(Math.random());
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = output;
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
-
+ import org.junit.*;
+
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = output;
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
-You can use ``Math.random`` and a cast to integer to return a random integer between some starting and ending value. The code below will create a random integer from 0 to 9. Remember that casting a double value to integer ``(int)`` will throw away any values after the decimal point.
+Getting a number between 0, inclusive, and 1, exclusive, may not seem all that
+useful. But we can expand the range easily enough. To see how, imagine you had
+less than a dollar to your name and you wanted to be richer—you’d want to find a
+way to **multiply** your money. If you could invest every penny you had in
+something that would multiply your money by 1,000 then instead of having
+somewhere between $0 and $1, then you’d have somewhere between $0 (inclusive—if
+you started with $0) and $1,000 (exclusive, since if you had even a fraction of
+a penny less than $1 multiplying by 1,000 would still leave you just a bit shy
+of $1,000.) If the investment multiplied your original money by a million,
+you’d have between $0 and $1,000,000! (But never *quite* $1,000,000.)
+
+Same trick applies to random numbers. The value ``Math.random`` returns is like
+the initial amount of money in your pocket, always a bit less than $1. If you
+multiply that value by any amount, it will stretch it into the range you want:
+
+|CodingEx| **Coding Exercise**
+
+.. activecode:: random-example-stretched
+ :language: java
+ :autograde: unittest
+
+ Try the following code. Run it several times to see what it prints each
+ time. Did you ever see 0.0? How about 1.0?
+ ~~~~
+ public class StretchedRandom
+ {
+ public static void main(String[] args)
+ {
+ System.out.println(Math.random() * 10);
+ System.out.println(Math.random() * 10);
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = output;
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
+
+You may have noticed that while the numbers generated were always in the range 0
+to 10, all the numbers probably had a lot a digits after the decimal point.
+Often we want a random integer, with nothing after the decimal point. Easy
+enough—casting a ``double`` to an ``int`` will throw away any values
+after the decimal point. For example,
+
+.. code-block:: java
+
+ // rnd is an integer in the range 0-9 (from 0 up to 10).
+ int rnd = (int)(Math.random()*10);
+
+Finally, what if we want a number in a range that doesn’t start with 0, say a
+number from 1 to 10 (including 10) instead of from 0 to 9 (including 9)? Since
+the size of the two ranges is the same, with ten numbers in each, all we need to
+do is shift from the range we’ve generated into the range we want. In other
+words, add the difference between the two ranges, 1 in this case.
+
+.. code-block:: java
+
+ // rnd is an integer in the range 1-10 (including 10).
+ int rnd = (int)(Math.random()*10) + 1;
|CodingEx| **Coding Exercise**
-
.. activecode:: randomRange
:language: java
:autograde: unittest
@@ -87,18 +403,21 @@ You can use ``Math.random`` and a cast to integer to return a random integer bet
~~~~
public class Test4
{
- public static void main(String[] args)
- {
- System.out.println((int) (Math.random() * 10));
- }
+ public static void main(String[] args)
+ {
+ System.out.println((int) (Math.random() * 10));
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
public void testContainsRange() throws IOException
{
@@ -106,36 +425,80 @@ You can use ``Math.random`` and a cast to integer to return a random integer bet
boolean passed = checkCodeContains("Math.random in range 1 to 10", target);
assertTrue(passed);
}
- }
-
+ }
+
.. note::
- - Math.random() returns a random number between 0.0-0.99.
-
- - **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number.
-
- - The range is the **(max number - min number + 1)**.
-
-
+ - Math.random() returns a random number between 0.0-0.99.
+
+ - **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number.
+
+ - The range is the **(max number - min number + 1)**.
+
+
Here are some examples that move a random number into a specific range.
-.. code-block:: java
+.. code-block:: java
// Math.random() returns a random number between 0.0-0.99.
double rnd = Math.random();
-
+
// rnd1 is an integer in the range 0-9 (including 9).
int rnd1 = (int)(Math.random()*10);
-
+
// rnd2 is in the range 1-10 (including 10). The parentheses are necessary!
int rnd2 = (int)(Math.random()*10) + 1;
-
+
// rnd3 is in the range 5-10 (including 10). The range is 10-5+1 = 6.
int rnd3 = (int)(Math.random()*6) + 5;
-
+
// rnd4 is in the range -10 up to 9 (including 9). The range is doubled (9 - -10 + 1 = 20) and the minimum is -10.
int rnd4 = (int)(Math.random()*20) - 10;
+So the general recipe for generating a random is to first stretch the value from
+``Math.random()`` until it’s in the right size range by multiplying by the size
+of the range. Then if you want an integer value, cast to ``int`` to discard the
+part after the decimal point. Then shift the value up by adding the minimum
+value. The table below shows some applications of that general recipe.
+
+.. rst-class:: random-recipes
+
+ .. list-table:: Random recipes
+ :widths: 70 10 10 10
+ :header-rows: 1
+
+ * - Expression
+ - Minimum (inclusive)
+ - Maximum (exclusive)
+ - Possible values
+ * - ``Math.random()``
+ - 0.0
+ - 1.0
+ - Over 9 quadrillion
+ * - ``Math.random() * 100``
+ - 0.0
+ - 100.0
+ - Over 9 quadrillion
+ * - ``(int)(Math.random() * 100)``
+ - 0
+ - 100
+ - 100
+ * - ``(int)(Math.random() * 50) + 25``
+ - 25
+ - 75
+ - 50
+ * - ``(int)(Math.random() * max)``
+ - 0
+ - max
+ - max
+ * - ``(int)(Math.random() * range) + min``
+ - min
+ - min + range
+ - range
+ * - ``(int)(Math.random() * (max - min)) + min``
+ - min
+ - max
+ - max - min
|Exercise| **Check your understanding**
@@ -146,23 +509,23 @@ Here are some examples that move a random number into a specific range.
:answer_c: Math.random() == 0.4
:correct: a
:feedback_a: This is true about 40% of the time since Math.random returns a value from 0 to not quite 1.
- :feedback_b: This will be true about 60% of the time.
- :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999).
+ :feedback_b: This will be true about 60% of the time.
+ :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999).
Which of the following would be true about 40% of the time?
-
+
.. mchoice:: qrand_2
:practice: T
:answer_a: ((int) (Math.random() * 5))
:answer_b: ((int) (Math.random() * 6))
:answer_c: ((int) (Math.random() * 5) + 1)
:correct: c
- :feedback_a: This would be a number between 0 and 4.
+ :feedback_a: This would be a number between 0 and 4.
:feedback_b: This would be a number between 0 and 5.
- :feedback_c: The first part would return a number between 0 and 4 and when you add 1 you get a number from 1 to 5 inclusive.
+ :feedback_c: The first part would return a number between 0 and 4 and when you add 1 you get a number from 1 to 5 inclusive.
Which of the following would return a random number from 1 to 5 inclusive?
-
+
.. mchoice:: qrand_3
:practice: T
:answer_a: ((int) (Math.random() * 10))
@@ -171,10 +534,10 @@ Here are some examples that move a random number into a specific range.
:correct: b
:feedback_a: This would be a number between 0 and 9.
:feedback_b: This would be a number between 0 and 10.
- :feedback_c: The first part would return a number between 0 and 9 and when you add 1 you get a number from 1 to 10 inclusive.
+ :feedback_c: The first part would return a number between 0 and 9 and when you add 1 you get a number from 1 to 10 inclusive.
Which of the following would return a random number from 0 to 10 inclusive?
-
+
.. mchoice:: qrand_4
:practice: T
:answer_a: Math.random() < 0.25
@@ -183,7 +546,7 @@ Here are some examples that move a random number into a specific range.
:correct: b
:feedback_a: This is true about 25% of the time, since it will be a number from 0 to not quite 1.
:feedback_b: This is true about 75% of the time, since it will be a number from 0 to not quite 1.
- :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999).
+ :feedback_c: Do not use == with double values! Remember that Math.random can return any number between 0 and not quite 1 (about .99999999).
Which of the following would be true about 75% of the time?
@@ -197,46 +560,28 @@ Here are some examples that move a random number into a specific range.
:answer_d: int rn = (int) (Math.random() * 36) + 25;
:answer_e: int rn = (int) (Math.random() * 60) + 25;
:correct: d
- :feedback_a: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 36.
- :feedback_b: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 60.
- :feedback_c: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. Here the min is 25. We want the minimum number to be 25, but the minimum number here would be 60.
+ :feedback_a: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 36.
+ :feedback_b: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. We want the minimum number to be 25, but the minimum number here would be 60.
+ :feedback_c: Remember that (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. Here the min is 25. We want the minimum number to be 25, but the minimum number here would be 60.
:feedback_d: Yes, (int)(Math.random()*36) + 25 moves the random number into a range of 36 numbers starting from a minimum number 25 up to 60. The range is (max number - min number + 1) which is (60-25 +1) = 36.
:feedback_e: This would give us random numbers from 25 to 85. Remember that you can compute the range you need with (max number - min number + 1).
Which of the following statements assigns a random integer between 25 and 60, inclusive, to rn?
-
-
-Other Math functions that you can use are:
-
-
-- int abs(int) : Returns the absolute value of an int value (which is the value of a number without its sign, for example Math.abs(-4) = 4).
-
-- double abs(double) : Returns the absolute value of a double value.
-
-- double pow(double, double) : Returns the value of the first parameter raised to the power of the second parameter.
-- double sqrt(double) : Returns the positive square root of a double value.
-- double random() : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!).
-.. |AP CS A Reference Sheet| raw:: html
-
- AP CS A Java Quick Reference Sheet
-
-These are all listed in the |AP CS A Reference Sheet| that you can use during the exam.
-
|Groupwork| Programming Challenge : Random Numbers
--------------------------------------------------
.. image:: Figures/lock.jpg
- :width: 100
+ :width: 100px
:align: left
:alt: lock
-
-You may have a combination lock on your locker at school where you have to spin the dial to 3 separate numbers from 0 up to 40. What if you forgot your combination? Would you be able to guess it?
-1. Write code that will generate 3 random integers from 0 up to 40 (but not including 40) using **Math.random()** in the Active Code window below. Run it a couple times to see it generate different numbers.
+You may have a combination lock on your locker at school where you have to spin the dial to 3 separate numbers from 0 up to 40. What if you forgot your combination? Would you be able to guess it?
+
+1. Write code that will generate 3 random integers from 0 up to 40 (but not including 40) using **Math.random()** in the Active Code window below. Run it a couple times to see it generate different numbers.
2. How many times would you need to run it to guess your combination correctly? Let's have the code compute the number of permutations possible in your combination lock using **Math.pow(number,exponent)**. For example, if you had 2 dials on your combination lock where each dial can be set to a digit from 0-9 (10 digits), there are 10\ :sup:`2` possible permutations. In Java, this would be written as **Math.pow(10,2)** which means 10 to the power of 2. If you start listing all the permutations possible, you can tell that there are 10\ :sup:`2` or 100 possible permutations for a 2 dial lock from 0-9.
@@ -249,124 +594,102 @@ You may have a combination lock on your locker at school where you have to spin
90, 91, 92, 93, 94, 95, 96, 97, 98, 99
-Now what about the combination lock for this challenge? It has 3 dials with 0-40 (not including 40) numbers possible on each dial. In general, the formula to use is NumbersPerDial\ :sup:`numberOfDials`. Write this using the **Math.pow()** method in your code and save it into a variable and print out.
+Now what about the combination lock for this challenge? You will need to spin the dial 3 times: once to the right, once to the left, and once to the right to 3 different numbers from 0 up to 40 (not including 40). In general, the formula to use is NumbersPerDial\ :sup:`numberOfDials`. Write this using the **Math.pow()** method in your code and save it into a variable and print out.
+
-
.. activecode:: challenge2-9-random-math
:language: java
:autograde: unittest
-
+
Complete the combination lock challenge below.
~~~~
public class MathChallenge
{
- public static void main(String[] args)
- {
- // 1. Use Math.random() to generate 3 integers from 0-40 (not including 40) and print them out.
-
-
- // 2. Calculate the number of combinations to choose 3 numbers between 0-40 (not including 40) using Math.pow() and print it out.
- // For example, Math.pow(10,2) is 10^2 and the number of permutations to choose 2 numbers between 0-9.
-
-
- }
- }
- ====
- import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- import java.util.ArrayList;
-
- public class RunestoneTests extends CodeTestHelper
- {
-
-
- @Test
- public void test1()
- {
- String output = getMethodOutput("main");
- String[] lines = output.split("\\s+");
-
- boolean passed = lines.length >= 2;
-
- passed = getResults("2+ lines of output", lines.length + " lines of output", "Expected output", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test2()
- {
- String output = getMethodOutput("main");
-
- boolean passed = output.contains("6400");
-
- passed = getResults("true", "" + passed, "Prints 40^3", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test3()
- {
- String code = getCode();
- int num = countOccurences(code, "Math.random()");
-
- boolean passed = num >= 3;
- passed = getResults("3 or more", ""+num, "Calls to Math.random()", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test4()
- {
- String code = getCode();
- int num = countOccurences(code, "Math.pow(");
-
- boolean passed = num >= 1;
- passed = getResults("1 or more", ""+num, "Calls to Math.pow(...)", passed);
- assertTrue(passed);
- }
-
- @Test
- public void test5() {
- int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
-
- String output = "";
- String[] lines;
- int[] nums = new int[4];
- int countUniqueNums = 0;
-
- for (int i = 0; i < 1000; i++) {
- output = getMethodOutput("main");
- lines = output.split("\\s+");
-
- if (lines.length == nums.length) {
- nums[0] = Integer.parseInt(lines[0]);
- nums[1] = Integer.parseInt(lines[1]);
- nums[2] = Integer.parseInt(lines[2]);
-
- min = Math.min(min, Math.min(nums[0], Math.min(nums[1], nums[2])));
- max = Math.max(max, Math.max(nums[0], Math.max(nums[1], nums[2])));
+ public static void main(String[] args)
+ {
+ // 1. Use Math.random() to generate 3 integers from 0-40 (not
+ // including 40) and print them out.
- if (nums[0] != nums[1] && nums[1] != nums[2])
- countUniqueNums++;
- }
- }
+ // 2. Calculate the number of combinations to choose 3 numbers between
+ // 0-40 (not including 40) using Math.pow() and print it out.
+ // For example, Math.pow(10,2) is 10^2 and the number of permutations
+ // to choose 2 numbers between 0-9.
- boolean passed = min == 0 && max == 39 && countUniqueNums > 5;
- getResults("Min: " + 0 + "\nMax: " + 39, "Min: " + min + "\nMax: " + max, "Checking random results", passed);
- assertTrue(passed);
- }
- }
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper {
+ @Test
+ public void test1() {
+ String output = getMethodOutput("main");
+ String[] lines = output.split("\\s+");
+
+ boolean passed = lines.length >= 2;
+
+ passed = getResults(
+ "2+ lines of output",
+ lines.length + " lines of output",
+ "Expected output",
+ passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2() {
+ String output = getMethodOutput("main");
+ boolean passed = output.contains("64000");
+ passed = getResults("true", "" + passed, "Prints result of 40^3", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3() {
+ String[] code = getCode().split("\n");
+ String expected = "Possible answers:\n(int) (Math.random() * 40)\n(int) (40 * Math.random())";
+ String actual = "";
+ int num = 0;
+
+ for (int i = 0; i < code.length; i++) {
+ if (code[i].contains("Math.random()") && code[i].contains("40")) {
+ actual += code[i].trim() + "\n";
+ if (code[i].contains("(int)"))
+ num++;
+ }
+ }
+
+ boolean passed = num >= 3;
+ passed = getResults(
+ expected,
+ actual,
+ "Creates 3 random numbers from 0 to 40 (not inclusive)",
+ passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test4() {
+ String code = getCode();
+ int num = countOccurences(code, "Math.pow(");
+
+ boolean passed = num >= 1;
+ passed = getResults("1 or more", "" + num, "Calls to Math.pow(...)", passed);
+ assertTrue(passed);
+ }
+ }
-Here's another challenge that is a lot of fun! Can you use random numbers to make dancing turtles? This idea was suggested by Zac Martin's class.
+Here's another challenge that is a lot of fun! Can you use random numbers to make dancing turtles? This idea was suggested by CSA teacher Zac Martin.
.. activecode:: challenge-2-9b-dancing-turtles
:language: java
:autograde: unittest
:datafile: turtleClasses.jar
- Complete the random numbers using Math.random() in the correct ranges to choose x, y coordinates for the turtle.
+ Complete the random numbers using Math.random() in the correct ranges to choose x, y coordinates and random color in the range of 0-255 for the turtle. Put on some music and watch your turtle dance!
~~~~
import java.util.*;
import java.awt.*;
@@ -375,49 +698,52 @@ Here's another challenge that is a lot of fun! Can you use random numbers to mak
{
public static void main(String[] args)
{
-
+
World world = new World(500,400);
Turtle yertle = new Turtle(world);
- // This is a loop that runs 10 times (you will learn to write loops in Unit 4)
- for(int i=1; i <= 10; i++)
- {
- // Can you choose a randomX between 0-500?
+ // This is a loop that runs 10 times (you will learn to write loops in
+ // Unit 4)
+ for(int i = 1; i <= 10; i++)
+ {
+ // Can you choose a randomX between 0-500?
// Can you adjust for the 20 pixel width of the turtle,
- // so it doesn't get cut off at the edges?
+ // so it doesn't get cut off at the edges?
// Move the range from 20 to 480.
- int randomX =
- // Can you choose a randomY between 0-400?
+ int randomX = 0;
+ // Can you choose a randomY between 0-400?
// Can you adjust for the 20 pixel height of the turtle,
// so it doesn't get cut off at the edges?
- int randomY =
-
+ int randomY = 0;
+
yertle.moveTo(randomX, randomY);
yertle.turnRight();
-
+
// Can you choose a random red, green, and blue value between 0-255?
- int randomR =
- int randomG =
- int randomB =
-
+ int randomR = 0;
+ int randomG = 0;
+ int randomB = 0;
+
yertle.setColor(new Color(randomR, randomG, randomB));
-
+
} // end of loop
- world.show(true);
+ world.show(true);
}
}
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("DancingTurtles");
}
-
@Test
public void test1()
{
@@ -425,19 +751,19 @@ Here's another challenge that is a lot of fun! Can you use random numbers to mak
int numRandom = countOccurences(code, "Math.random()");
boolean passed = numRandom >= 5;
- passed = getResults("5+", ""+numRandom, "5+ calls to Math.random()", passed);
+ passed = getResults("5+", "" + numRandom, "5+ calls to Math.random()", passed);
assertTrue(passed);
}
@Test
public void test2()
{
- boolean passed = checkCodeContainsNoRegex("Random numbers for 0-255 colors (256 values)","Math.random() * 256");
- assertTrue(passed);
+ boolean passed =
+ checkCodeContainsNoRegex(
+ "Random numbers for 0-255 colors (256 values)", "Math.random() * 256");
+ assertTrue(passed);
}
}
-
-
Summary
-------------------
@@ -448,12 +774,10 @@ Summary
- **int abs(int)** : Returns the absolute value of an int value (which means no negatives).
- **double abs(double)** : Returns the absolute value of a double value.
- - **double pow(double, double)** : Returns the value of the first parameter raised to the power of the second parameter.
+ - **double pow(double, double)** : Returns the value of the first parameter raised to the power of the second parameter.
- **double sqrt(double)** : Returns the positive square root of a double value.
- **double random()** : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0)!
-
-- The values returned from Math.random can be manipulated to produce a random int or double in a defined range.
-
-- **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number. The range is the **(max number - min number + 1)**. For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: (int)(Math.random()*6) + 5).
+- The values returned from Math.random can be manipulated to produce a random int or double in a defined range.
+- **(int)(Math.random()*range) + min** moves the random number into a range starting from a minimum number. The range is the **(max number - min number + 1)**. For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: ``(int)(Math.random()*6) + 5``.
diff --git a/_sources/Unit3-If-Statements/Exercises.rst b/_sources/Unit3-If-Statements/Exercises.rst
index ab1b19f5c..c6b3b49b7 100644
--- a/_sources/Unit3-If-Statements/Exercises.rst
+++ b/_sources/Unit3-If-Statements/Exercises.rst
@@ -1,15 +1,15 @@
.. qnum::
- :prefix: 3-11-
+ :prefix: 3-12-
:start: 1
-
+
Multiple Choice Exercises
=================================
Easier Multiple Choice Questions
----------------------------------
-These problems are easier than most of those that you will usually see on the AP CS A exam.
+These problems are easier than most of those that you will usually see on the AP CSA exam.
.. mchoice:: qce_1
:practice: T
@@ -17,42 +17,42 @@ These problems are easier than most of those that you will usually see on the AP
: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_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.
+ :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
+
+ .. code-block:: java
if (x < 0)
{
System.out.println("x is negative");
}
- else if (x == 0)
+ else if (x == 0)
{
- System.out.println("x is zero");
+ System.out.println("x is zero");
}
- else
+ else
{
System.out.println("x is positive");
}
-
+
.. mchoice:: qce_2
:practice: T
:answer_a: first case
- :answer_b: second 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.
+ :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?
- What is printed when the following code executes and x equals 4 and y equals 3?
-
- .. code-block:: java
+ .. code-block:: java
- if (!(x < 3 || y > 2))
+ if (!(x < 3 || y > 2))
System.out.println("first case");
- else
+ else
System.out.println("second case");
.. mchoice:: qce_3
@@ -63,47 +63,66 @@ These problems are easier than most of those that you will usually see on the AP
: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_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.
+ :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
+ What is the value of grade when the following code executes and score is 80?
- if (score >= 90) grade = "A";
- if (score >= 80) grade = "B";
- if (score >= 70) grade = "C";
- if (score >= 60) grade = "D";
- else grade = "E";
+ .. code-block:: java
+
+ if (score >= 90)
+ {
+ grade = "A";
+ }
+ if (score >= 80)
+ {
+ grade = "B";
+ }
+ if (score >= 70)
+ {
+ grade = "C";
+ }
+ if (score >= 60)
+ {
+ grade = "D";
+ }
+ else
+ {
+ grade = "E";
+ }
.. mchoice:: qce_4
:practice: T
:answer_a: first case
:answer_b: second case
- :answer_c: You will get a error because you can't divide by zero.
+ :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_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
+ What is printed when the following code executes and x has been set to zero and y is set to 3?
- if (x > 0 || (y / x) == 3)
- System.out.println("first case");
- else
- System.out.println("second case");
+ .. code-block:: java
+
+ if (x > 0 || (y / x) == 3)
+ {
+ System.out.println("first case");
+ }
+ else
+ {
+ System.out.println("second case");
+ }
Medium Multiple Choice Questions
----------------------------------
-These problems are similar to those you will see on the AP CS A exam.
+These problems are similar to those you will see on the AP CSA exam.
.. mchoice:: qcm_1
:practice: T
@@ -114,41 +133,41 @@ These problems are similar to those you will see on the AP CS A exam.
: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_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) ?
-
+ Which of the following expressions is equivalent to !(c || d) ?
+
.. mchoice:: qcm_2
:practice: T
:answer_a: x = 0;
- :answer_b: if (x > 2) x *= 2;
- :answer_c: if (x > 2) x = 0;
- :answer_d: if (x > 2) x = 0; else x *= 2;
+ :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_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?
-
+ Which of the following is equivalent to the code segment below?
+
.. code-block:: java
- if (x > 2)
+ if (x > 2)
x = x * 2;
- if (x > 4)
+ if (x > 4)
x = 0;
.. mchoice:: qcm_3
:practice: T
:answer_a: x = 0;
- :answer_b: if (x > 0) x = 0;
- :answer_c: if (x < 0) x = 0;
- :answer_d: if (x > 0) x = -x; else x = 0;
- :answer_e: if (x < 0) x = 0; else x = -1;
+ :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.
@@ -156,13 +175,13 @@ These problems are similar to those you will see on the AP CS A exam.
: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?
-
+ Which of the following is equivalent to the code segment below?
+
.. code-block:: java
- if (x > 0)
+ if (x > 0)
x = -x;
- if (x < 0)
+ if (x < 0)
x = 0;
.. mchoice:: qcm_4
@@ -174,20 +193,20 @@ These problems are similar to those you will see on the AP CS A exam.
:answer_e: I, II, and III
:correct: a
:feedback_a: Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice II won't work since if you had a score of 94, it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". Choice III uses ifs with else if to make sure that only one conditional is executed.
- :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if.
- :feedback_c: III is one of the correct answers. However, choice I is also correct. Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice III uses ifs with else if to make sure that the only one conditional is executed.
+ :feedback_b: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if.
+ :feedback_c: III is one of the correct answers. However, choice I is also correct. Choice I uses multiple if's with logical ands in the conditions to check that the numbers are in range. Choice III uses ifs with else if to make sure that the only one conditional is executed.
:feedback_d: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if.
:feedback_e: Choice II won't work since if you had a score of 94 it would first assign the grade to an "A" but then it would execute the next if and change the grade to a "B" and so on until the grade was set to a "C". This could have been fixed by using else if instead of just if.
At a certain high school students receive letter grades based on the following scale: 93 or above is an A, 84 to 92 is a B, 75 to 83 is a C, and below 75 is an F. Which of the following code segments will assign the correct string to grade for a given integer score?
-
+
.. code-block:: java
I. if (score >= 93)
grade = "A";
- if (score >= 84 && score <=92)
+ if (score >= 84 && score < 93)
grade = "B";
- if (score >=75 && score <= 83)
+ if (score >=75 && score < 84)
grade = "C";
if (score < 75)
grade = "F";
@@ -205,50 +224,23 @@ These problems are similar to those you will see on the AP CS A exam.
grade = "A";
else if (score >= 84)
grade = "B";
- else if (score >=75)
+ else if (score >= 75)
grade = "C";
else
grade = "F";
-
+
Hard Multiple Choice Questions
----------------------------------
-These problems are harder than most of those that you will usually see on the AP CS A exam.
-
-
-
-.. .. mchoice:: qch_2
- :practice: T
- :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);
- }
- }
+These problems are harder than most of those that you will usually see on the AP CSA exam.
.. mchoice:: qch_3
:practice: T
:answer_a: (x > 15 && x < 18) && (x > 10)
:answer_b: (y < 20) || (x > 15 && x < 18)
:answer_c: ((x > 10) || (x > 15 && x < 18)) || (y < 20)
- :answer_d: (x < 10 && y > 20) && (x < 15 || x > 18)
+ :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.
@@ -256,17 +248,17 @@ These problems are harder than most of those that you will usually see on the AP
:feedback_d: This is the negation of the original statement, thus returning incorrect values.
Assuming that x and y have been declared as valid integer values, which of the following is equivalent to this statement?
-
+
.. code-block:: java
(x > 15 && x < 18) || (x > 10 || y < 20)
-
+
.. mchoice:: qch_4
:practice: T
:answer_a: first
:answer_b: first second
:answer_c: first second third
- :answer_d: first third
+ :answer_d: first third
:answer_e: third
:correct: d
:feedback_a: This will print, but so will something else.
@@ -274,48 +266,44 @@ These problems are harder than most of those that you will usually see on the AP
: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?
-
+
+ What would the following print?
+
.. code-block:: java
-
+
int x = 3;
int y = 2;
- if (x > 2)
+ if (x > 2)
x++;
- if (y > 1)
+ if (y > 1)
y++;
- if (x > 2)
+ if (x > 2)
System.out.print("first ");
- if (y < 3)
+ if (y < 3)
System.out.print("second ");
System.out.print("third");
-
+
.. mchoice:: qch_5
:practice: T
- :answer_a: first
+ :answer_a: first
:answer_b: second
- :answer_c: first 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_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?
-
+
+ What would the following print?
+
.. code-block:: java
-
+
int x = 3;
int y = 2;
- if (y / x > 0)
+ if (y / x > 0)
System.out.print("first ");
System.out.print("second ");
-
-
-
-
-
+The Mark Complete button and green check mark are intentionally not included in the Exercises.html pages because these pages may be used for many quiz-bank exercises.
diff --git a/_sources/Unit3-If-Statements/Figures/Condition-three.png b/_sources/Unit3-If-Statements/Figures/Condition-three.png
index a9dd5cceb..8d1d4366c 100644
Binary files a/_sources/Unit3-If-Statements/Figures/Condition-three.png and b/_sources/Unit3-If-Statements/Figures/Condition-three.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/Condition-two.png b/_sources/Unit3-If-Statements/Figures/Condition-two.png
index ba2e3e0e9..eae9b433c 100644
Binary files a/_sources/Unit3-If-Statements/Figures/Condition-two.png and b/_sources/Unit3-If-Statements/Figures/Condition-two.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/Condition.png b/_sources/Unit3-If-Statements/Figures/Condition.png
index b3091dbc2..c4d50b11e 100644
Binary files a/_sources/Unit3-If-Statements/Figures/Condition.png and b/_sources/Unit3-If-Statements/Figures/Condition.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/adventure.jpg b/_sources/Unit3-If-Statements/Figures/adventure.jpg
new file mode 100644
index 000000000..614f27fb6
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/adventure.jpg differ
diff --git a/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png b/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png
new file mode 100644
index 000000000..260d01714
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/ap-frq-scoring.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png
new file mode 100644
index 000000000..a651f586c
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme1.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png
new file mode 100644
index 000000000..4659a4297
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-theme2.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png
new file mode 100644
index 000000000..c6c0e0689
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-1.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png
new file mode 100644
index 000000000..7addb7f9e
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/posttest-unlucky-2.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png
new file mode 100644
index 000000000..437a67b53
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym1.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png
new file mode 100644
index 000000000..86b7c0b12
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-gym2.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png
new file mode 100644
index 000000000..16da5988e
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-1.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png
new file mode 100644
index 000000000..d3e0e511b
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/experiment/pretest-lucky-2.png differ
diff --git a/_sources/Unit3-If-Statements/Figures/s1ands2.jpg b/_sources/Unit3-If-Statements/Figures/s1ands2.jpg
new file mode 100644
index 000000000..30c2fe414
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/s1ands2.jpg differ
diff --git a/_sources/Unit3-If-Statements/Figures/s2ands3.jpg b/_sources/Unit3-If-Statements/Figures/s2ands3.jpg
new file mode 100644
index 000000000..5c7cf62d4
Binary files /dev/null and b/_sources/Unit3-If-Statements/Figures/s2ands3.jpg differ
diff --git a/_sources/Unit3-If-Statements/frq-game-score.rst b/_sources/Unit3-If-Statements/frq-game-score.rst
new file mode 100644
index 000000000..46bb3ec6c
--- /dev/null
+++ b/_sources/Unit3-If-Statements/frq-game-score.rst
@@ -0,0 +1,331 @@
+
+Unit 3 Free Response Question (FRQ) Game Practice
+====================================================
+
+.. index::
+ single: free response questions
+ single: FRQ
+
+The AP CSA exam has 4 free response questions (FRQs) where you have to write Java code in 1.5 hours. The first FRQ is about Methods and Control Structures using expressions, methods, loops, and if statements. In the last unit, we tried a simplified FRQ 1 part a about the points earned in a video game with 3 levels using the class ``Level``. You will now try the complete 2022 FRQ 1 part a from https://apcentral.collegeboard.org/media/pdf/ap22-frq-computer-science-a.pdf.
+
+
+FRQ 1 Part A Description (2022)
+---------------------------------
+
+This question involves simulation of the play and scoring of a single-player video game. In the game, a player attempts to complete three levels. A level in the game is represented by the ``Level`` class.
+
+.. code-block:: java
+
+ public class Level
+ {
+ /** Returns true if the player reached the goal on this level and returns false otherwise */
+ public boolean goalReached()
+ { /* implementation not shown */ }
+
+ /** Returns the number of points (a positive integer) recorded for this level */
+ public int getPoints()
+ { /* implementation not shown */ }
+
+ // There may be instance variables, constructors, and methods that are not shown.
+ }
+
+Play of the game is represented by the ``Game`` class. You will write a method of the Game class.
+
+.. code-block:: java
+
+ public class Game
+ {
+ private Level levelOne;
+ private Level levelTwo;
+ private Level levelThree;
+
+ /** Postcondition: All instance variables have been initialized. */
+ public Game()
+ { /* implementation not shown */ }
+
+ /** Returns true if this game is a bonus game and returns false otherwise */
+ public boolean isBonus()
+ { /* implementation not shown */ }
+
+ /** Simulates the play of this Game (consisting of three levels) and updates all relevant
+ * game data
+ */
+ public void play()
+ { /* implementation not shown */ }
+
+ /** Returns the score earned in the most recently played game, as described in part (a) */
+ public int getScore()
+ { /* to be implemented in part (a) */ }
+
+ /** Simulates the play of num games and returns the highest score earned, as
+ * described in part (b)
+ * Precondition: num > 0
+ */
+ public int playManyTimes(int num)
+ { /* to be implemented in part (b) */ }
+
+ // There may be instance variables, constructors, and methods that are not shown.
+ }
+
+In part a, you will write the ``getScore`` method, which returns the score for the most recently played game. Each game consists of three levels. The score for the game is computed using the following helper methods.
+
+- The ``isBonus`` method of the Game class returns true if this is a bonus game and returns false otherwise.
+
+- The ``goalReached`` method of the Level class returns true if the goal has been reached on a particular level and returns false otherwise.
+
+- The ``getPoints`` method of the Level class returns the number of points recorded on a particular level. Whether or not recorded points are earned (included in the game score) depends on the rules of the game, which follow.
+
+The ``score`` for the game is computed according to the following rules.
+
+- Level one points are earned only if the level one goal is reached.
+
+- Level two points are earned only if both the level one and level two goals are reached.
+
+- Level three points are earned only if the goals of all three levels are reached.
+
+- The score for the game is the sum of the points earned for levels one, two, and three.
+
+- If the game is a bonus game, the score for the game is tripled.
+
+Warm up Exercises
+-------------------
+
+FRQs often have a lot of dense text. It is a good idea to highlight important keywords and the methods and variables that you will need.
+
+1. The first step is to determine what they are asking you to write.
+2. The second step is to determine which methods given in the problem description you need to use in your solution.
+
+Let's practice this below.
+
+.. mchoice:: frq_which_method
+ :answer_a: getPoints()
+ :answer_b: goalReached()
+ :answer_c: play()
+ :answer_d: getScore()
+ :correct: d
+ :random:
+ :feedback_a: The ``getPoints()`` method is given to you to get the points for a level.
+ :feedback_b: The ``goalReached()`` method is given to you to check if the goal is reached for a level.
+ :feedback_c: The ``play()`` method is given to you to simulate the play of the game.
+ :feedback_d: Correct, the ``getScore()`` method is the one you will write for part a.
+
+ Which method are you asked to write for part a?
+
+.. clickablearea:: frqifs
+ :question: Select the phrases below which will probably correspond to an if clause of a conditional statement.
+ :iscode:
+ :feedback: Look for the word if
+
+ :click-incorrect:The score for the game is computed:endclick: according to the following rules.
+
+ - Level one points are earned only :click-correct:if the level one goal is reached.:endclick:
+ - Level two points are earned only :click-correct:if both the level one and level two goals are reached.:endclick:
+ - Level three points are earned only :click-correct:if the goals of all three levels are reached.:endclick:
+ - The score for the game is :click-incorrect:the sum of the points earned for levels one, two, and three.:endclick:
+ - :click-correct:If the game is a bonus game:endclick: , the score for the game is tripled.
+
+
+.. mchoice:: frq_which_methods_used
+ :answer_a: getPoints()
+ :answer_b: goalReached()
+ :answer_c: isBonus()
+ :answer_d: getScore()
+ :correct: a,b,c
+ :feedback_a: The getPoints() method is given to you to get the points for a level.
+ :feedback_b: The goalReached() method is given to you to check if the goal is reached for a level.
+ :feedback_c: The isBonus() method is given to you to check if the game is a bonus game.
+ :feedback_d: The getScore() method is the one you will write for part a.
+
+ What are some methods given to you that you will need to use for part a?
+
+There are two classes given to you in this FRQ. Which method belongs to each class?
+
+.. dragndrop:: frq_method_class_match
+ :feedback: Review the FRQ description above.
+ :match_1: getPoints()|||Level
+ :match_2: isBonus()|||Game
+
+ Drag the method from the left and drop it on the correct class that it belongs to on the right. Click the "Check Me" button to see if you are correct.
+
+Notice that the ``Game`` class has 3 instance variables to represent each level, ``levelOne``, ``levelTwo``, and ``levelThree`` which are object of class type ``Level``. You will need to use these variables to get their points and check if the goal is reached for each level.
+
+.. mchoice:: frq_call_method
+ :answer_a: goalReached()
+ :answer_b: levelOne.goalReached()
+ :answer_c: Level.goalReached()
+ :answer_d: goalReached(levelOne)
+ :random:
+ :correct: b
+ :feedback_a: The goalReached() method is a non-static method of the Level class. You need to call it with an object of the class.
+ :feedback_b: Correct, this calls the levelOne object's goalReached() method.
+ :feedback_c: The goalReached() method is a non-static method of the ``Level`` class. You need to call it with an object of the class, not the class name.
+ :feedback_d: The goalReached() method does not take an argument.
+
+ How would you call the ``goalReached()`` method of the ``levelOne`` object?
+
+Let's simplify the problem by first writing the code to add the points for ``levelOne`` to a variable called ``score``.
+
+.. mchoice:: frq_expression
+ :answer_a: score += levelOnePoints
+ :answer_b: score += levelOne.getPoints()
+ :answer_c: score = score + Level.getPoints()
+ :answer_d: score = Level.points
+ :random:
+ :correct: b
+ :feedback_a: There is no levelOnePoints variable.
+ :feedback_b: Correct, this adds levelOne's getPoints() to score.
+ :feedback_c: The getPoints()`` method is a non-static method of the Level class. You need to call it with an object of the class, not the class name.
+ :feedback_d: There is no points instance variable.
+
+ Which expression would add the points for ``levelOne`` into a variable called ``score``?
+
+Solve the Problem
+-------------------
+
+Let's write the code for the ``getScore()`` method. The method should use the ``goalReached()`` and ``getPoints()`` methods of the ``Level`` class to calculate the score for the game. It will need to check if the goal is reached for each level using the ``levelOne``, ``levelTwo``, and ``levelThree`` objects and add the points for each level to the score. If the game is a bonus game, which can be checked with the ``isBonus()`` method (no object needed since it is in the same class), the score will be tripled. At the end of the method, a ``return`` statement will return the score to the main method to be printed out.
+
+.. activecode:: frq-getScore
+ :language: java
+ :autograde: unittest
+
+ Write the code for the ``getScore()`` method of the ``Game`` class. The method should use the ``goalReached()`` and ``getPoints()`` methods of the ``levelOne``, ``levelTwo`` and ``levelThree`` objects to calculate the score for the game. If it is a ``isBonus()`` game, the score should be tripled.
+ ~~~~
+ public class Game
+ {
+ /* the Level objects */
+ private Level levelOne;
+ private Level levelTwo;
+ private Level levelThree;
+ private boolean bonus;
+
+ /* Complete the getScore() method below */
+ public int getScore()
+ {
+ int score = 0;
+ // Write your code here
+
+
+
+ return score;
+ }
+
+
+ public Game( int p1, boolean g1, int p2, boolean g2, int p3, boolean g3, boolean b )
+ {
+ levelOne = new Level( p1, g1 );
+ levelTwo = new Level( p2, g2 );
+ levelThree = new Level( p3, g3 );
+ bonus = b;
+ }
+
+ public boolean isBonus()
+ {
+ return bonus;
+ }
+
+ public static void main(String[] args)
+ {
+ // These are the AP test cases given in the problem description
+ Game g1 = new Game(200,true,100,true,500,true,true);
+ // This should print out 2400
+ System.out.println( g1.getScore() );
+
+ Game g2 = new Game(200,true,100,true,500,false,false);
+ // This should print out 300
+ System.out.println( g2.getScore() );
+
+ Game g3 = new Game(200,true,100,false,500,true,true);
+ // This should print out 600
+ System.out.println( g3.getScore() );
+
+ Game g4 = new Game(200,false,100,true,500,true,false);
+ // This should print out 0
+ System.out.println( g4.getScore() );
+
+
+ }
+
+ }
+ class Level
+ {
+ private int points;
+ private boolean goal;
+
+ /** Constructor for the Level class */
+ public Level(int p, boolean g)
+ {
+ points = p;
+ goal = g;
+ }
+
+ /** Returns true if the player reached the goal on this level and returns false otherwise */
+ public boolean goalReached()
+ { return goal; }
+
+ /** Returns the number of points recorded for this level */
+ public int getPoints()
+ { return points; }
+ }
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Game");
+ // This sets default values for when objects are instantiated
+ Object[] values = new Object[] {100, true, 100, true, 100, false, true};
+ setDefaultValues(values);
+ }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "2400\n300\n600\n0\n";
+
+ boolean passed = getResults(expect, output, "Output from main");
+ assertTrue(passed);
+ }
+ @Test
+ public void checkCodeContains1()
+ {
+ boolean passed = checkCodeContains(
+ "call to levelThree.getPoints()", "levelThree.getPoints()");
+ assertTrue(passed);
+ }
+ @Test
+ public void checkCodeContains2()
+ {
+ boolean passed = checkCodeContains(
+ "call to levelThree.goalReached()", "levelThree.goalReached()");
+ assertTrue(passed);
+ }
+ @Test
+ public void testCall() throws IOException
+ {
+ int output = Integer.parseInt(
+ getMethodOutput("getScore"));
+ int expect = 600;
+
+ boolean passed = getResults(expect, output, "Checking another call to getScore()");
+ assertTrue(passed);
+ }
+ }
+
+
+AP Scoring Rubric
+--------------------
+
+Here is the AP rubric for this problem. Did your code meet the requirements for all 4 points? Notice that even a partial solution would get some of the points. It is not all or nothing. In class, your teacher may have you grade each others' code.
+
+
+.. figure:: Figures/ap-frq-scoring.png
+ :width: 760px
+ :align: center
+ :alt: AP Rubric for part a
+ :figclass: align-center
+
+ Figure 1: AP Rubric
\ No newline at end of file
diff --git a/_sources/Unit3-If-Statements/magpie-exercises.rst b/_sources/Unit3-If-Statements/magpie-exercises.rst
index 27f9e34d7..4ad58f737 100644
--- a/_sources/Unit3-If-Statements/magpie-exercises.rst
+++ b/_sources/Unit3-If-Statements/magpie-exercises.rst
@@ -15,7 +15,7 @@ Mixed Up Code Practice
:adaptive:
:noindent:
- The following program segment should print 4 random responses using if/else statements, but the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The following program segment should print 4 random responses using if/else statements, but the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
private String getRandomResponse()
{
@@ -26,16 +26,23 @@ Mixed Up Code Practice
int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
String response = "";
=====
- if (whichResponse == 0) {
+ if (whichResponse == 0)
+ {
response = "Interesting, tell me more.";
=====
- } else if (whichResponse == 1) {
+ }
+ else if (whichResponse == 1)
+ {
response = "Hmmm.";
=====
- } else if (whichResponse == 2) {
+ }
+ else if (whichResponse == 2)
+ {
response = "Do you really think so?";
=====
- } else if (whichResponse == 3) {
+ }
+ else if (whichResponse == 3)
+ {
response = "You don't say.";
}
=====
diff --git a/_sources/Unit3-If-Statements/magpie1.rst b/_sources/Unit3-If-Statements/magpie1.rst
index b94313ded..a7bdc84fe 100644
--- a/_sources/Unit3-If-Statements/magpie1.rst
+++ b/_sources/Unit3-If-Statements/magpie1.rst
@@ -1,7 +1,7 @@
.. qnum::
:prefix: lab-1a-
:start: 1
-
+
.. highlight:: java
:linenothreshold: 4
@@ -15,8 +15,8 @@ Lab Requirement
.. |Magpie Chatbot Lab| raw:: html
Magpie Chatbot Lab
-
-As of 2014-2015 the Advanced Placement Computer Science A course must include at least 20 hours of hands-on labs. In 2014, 3 recommended labs were created, Magpie, Picture, and Elevens, and in 2019-20, 4 more labs were created, Consumer Review, Steganography (an extension of PictureLab), Celebrity, and Data. Your teacher may choose to do any of these labs or their own labs to complete at least 20 hours of labs. See https://apcentral.collegeboard.org/courses/ap-computer-science-a/classroom-resources/lab-resource-page for the student guides for each of these labs.
+
+As of 2014-2015 the Advanced Placement Computer Science A course must include at least 20 hours of hands-on labs. In 2014, 3 recommended labs were created, Magpie, Picture, and Elevens, and in 2019-20, 4 more labs were created, Consumer Review, Steganography (an extension of PictureLab), Celebrity, and Data. Your teacher may choose to do any of these labs or their own labs to complete at least 20 hours of labs. See https://apcentral.collegeboard.org/courses/ap-computer-science-a/classroom-resources/lab-resource-page for the student guides for each of these labs.
If your class does all or part of the Magpie Lab, here is the College Board student guide for the |Magpie Chatbot Lab| as a pdf. Your teacher will provide the lab code for you which is also in the next pages. The particular code in each of these labs will not be on the exam, but the concepts covered by the labs will be on the exam.
@@ -24,34 +24,46 @@ Magpie Lab Description
----------------------
-
-The Magpie lab allows you to work with the ``String`` class and conditionals with a **chatbot**. A **chatbot** is a computer program that tries to hold a conversation with a user. This chapter will walk you through the activities in the Magpie chatbot lab.
+
+The Magpie lab allows you to work with the ``String`` class and conditionals with a **chatbot**. A **chatbot** is a computer program that tries to hold a conversation with a user. This chapter will walk you through the activities in the Magpie chatbot lab.
The first activity in Magpie is to explore some existing chatbots. We encourage you to work in pairs or groups on this activity.
Activity 1: Exploring Chatbots
------------------------------
+.. |ELIZA| raw:: html
+
+ ELIZA
+
+.. |ALICE| raw:: html
+
+ A.L.I.C.E.
+
.. |chatbots| raw:: html
- chatbots here
-
-1. Working in pairs or groups, try out some |chatbots|.
-
+ chatbots
+
+1. Working in pairs or groups, try out some chatbots, for example:
+
+ - |ELIZA| the therapist bot from the 1970s:
+ - |ALICE| from the 1990s:
+ - Modern |chatbots| which use AI and machine learning
+
2. Record the chatbot response to each of the following.
-* Where do you come from?
-* asdfghjkl;
-* My mother and I talked last night.
-* The weather is nice.
-* I said no!
+ * Where do you come from?
+ * asdfghjkl;
+ * My mother and I talked last night.
+ * The weather is nice.
+ * I said no!
-3. Ask the chatbot other questions.
+3. Ask the chatbot other questions.
-* Record the most interesting response.
-* Record the most peculiar response.
+ * Record the most interesting response.
+ * Record the most peculiar response.
-4. Work with another student or group to have two chatbots chat with each other. Type the responses from one chatbot into the input area for the other and vice-versa.
+4. Work with another student or group to have two chatbots chat with each other. Type the responses from one chatbot into the input area for the other and vice-versa.
-5. **Keywords**: Some chatbots look for particular keywords and respond based on those keywords. What are some of the keywords that your chatbot seems to be responding to? Why do you think it responds to those keywords?
+5. **Keywords**: Some chatbots look for particular keywords and respond based on those keywords. What are some of the keywords that your chatbot seems to be responding to? Why do you think it responds to those keywords?
diff --git a/_sources/Unit3-If-Statements/magpie2.rst b/_sources/Unit3-If-Statements/magpie2.rst
index fc73c0924..42d56a1ad 100644
--- a/_sources/Unit3-If-Statements/magpie2.rst
+++ b/_sources/Unit3-If-Statements/magpie2.rst
@@ -1,3 +1,5 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: lab-1b-
:start: 1
@@ -5,14 +7,14 @@
.. highlight:: java
:linenothreshold: 4
-
+|Time45|
Activity 2: Running Simplified Magpie Code
===========================================
-The College Board activity asks you to enter input using the ``Scanner`` class and record the responses. But, instead you can run this simplified version below and just call the ``getResponse`` method with each string as input as shown in the ``main`` method below.
+The College Board activity asks you to enter input using the ``Scanner`` class and record the responses. But, instead you can run this simplified version below and just call the ``getResponse`` method with each string as input as shown in the ``main`` method below.
-Up until now, all our code has been in the main method. In this lab, there are a couple methods. The main method creates a Magpie object called maggie, and calls its methods maggie.getGreeting() and maggie.getResponse(input) giving one of the following strings as input and printing its response.
+In this lab, the main method creates a Magpie object called maggie, and calls its methods maggie.getGreeting() and maggie.getResponse(input) where the input can be one of the following strings as input and a response is printed out.
* My mother and I talked last night.
* I said no!
@@ -23,64 +25,99 @@ Run the following code and see the responses to these 4 inputs.
.. activecode:: lc-magpie2
:language: java
+ :autograde: unittest
+ Run to see the results. Try changing the input in main.
+ ~~~~
public class Magpie2
{
- public String getGreeting()
- {
- return "Hello, let's talk.";
- }
+ public String getGreeting()
+ {
+ return "Hello, let's talk.";
+ }
+
+ public String getResponse(String statement)
+ {
+ String response = "";
+ if (statement.indexOf("no") >= 0)
+ {
+ response = "Why so negative?";
+ } else if (statement.indexOf("mother") >= 0
+ || statement.indexOf("father") >= 0
+ || statement.indexOf("sister") >= 0
+ || statement.indexOf("brother") >= 0)
+ {
+ response = "Tell me more about your family.";
+ }
+ else
+ {
+ response = getRandomResponse();
+ }
+ return response;
+ }
+
+ private String getRandomResponse()
+ {
+ final int NUMBER_OF_RESPONSES = 4;
+ double r = Math.random();
+ int whichResponse = (int) (r * NUMBER_OF_RESPONSES);
+ String response = "";
+
+ if (whichResponse == 0)
+ {
+ response = "Interesting, tell me more.";
+ }
+ else if (whichResponse == 1)
+ {
+ response = "Hmmm.";
+ }
+ else if (whichResponse == 2)
+ {
+ response = "Do you really think so?";
+ }
+ else if (whichResponse == 3)
+ {
+ response = "You don't say.";
+ }
+ return response;
+ }
+
+ public static void main(String[] args)
+ {
+ Magpie2 maggie = new Magpie2();
+
+ System.out.println(maggie.getGreeting());
+ System.out.println(">My mother and I talked last night.");
+ System.out.println(
+ maggie.getResponse("My mother and I talked last night."));
+ System.out.println(">I said no.");
+ System.out.println(maggie.getResponse("I said no!"));
+ System.out.println(">The weather is nice.");
+ System.out.println(maggie.getResponse("The weather is nice."));
+ System.out.println(">Do you know my brother?");
+ System.out.println(maggie.getResponse("Do you know my brother?"));
+ }
+ }
- 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;
- }
+ ====
+ // should pass if/when they run code
+ import static org.junit.Assert.*;
- 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;
- }
+ import org.junit.*;
- public static void main(String[] args)
- {
- Magpie2 maggie = new Magpie2();
-
- System.out.println(maggie.getGreeting());
- System.out.println(">My mother and I talked last night.");
- System.out.println(maggie.getResponse("My mother and I talked last night."));
- System.out.println(">I said no.");
- System.out.println(maggie.getResponse("I said no!"));
- System.out.println(">The weather is nice.");
- System.out.println(maggie.getResponse("The weather is nice."));
- System.out.println(">Do you know my brother?");
- System.out.println(maggie.getResponse("Do you know my brother?"));
- }
- }
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Hello, let's talk....";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
.. |chatbots| raw:: html
@@ -89,25 +126,98 @@ Run the following code and see the responses to these 4 inputs.
.. |Java visualizer Chatbot| raw:: html
Java visualizer Chatbot
-
-When different methods are called from the main method, the control flows to these methods and then comes back to main exactly where it was left when the methods finish.
-Click on this cool |Java visualizer Chatbot| to step through the code. Click on the Forward button at the bottom of the code to step through the code to see the flow of control from the main method to the other methods and back.
+When different methods are called from the main method, the control flows to these methods and then comes back to main exactly where it was left when the methods finish. Click on the cool |Java visualizer Chatbot| below to step through the code. Click on the Forward button at the bottom of the code to step through the code to see the flow of control from the main method to the other methods and back.
+.. codelens:: magpieviz
+ :language: java
+ :optional:
-.. |Magpie lab on repl.it| raw:: html
+ public class Magpie2
+ {
+ public String getGreeting()
+ {
+ return "Hello, let's talk.";
+ }
- Magpie lab on repl.it
+ public String getResponse(String statement)
+ {
+ String response = "";
+ if (statement.indexOf("no") >= 0)
+ {
+ response = "Why so negative?";
+ }
+ else if (statement.indexOf("mother") >= 0
+ || statement.indexOf("father") >= 0
+ || statement.indexOf("sister") >= 0
+ || statement.indexOf("brother") >= 0)
+ {
+ response = "Tell me more about your family.";
+ }
+ else
+ {
+ response = getRandomResponse();
+ }
+ return response;
+ }
+
+ private String getRandomResponse()
+ {
+ final int NUMBER_OF_RESPONSES = 4;
+ double r = Math.random();
+ int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
+ String response = "";
+
+ if (whichResponse == 0)
+ {
+ response = "Interesting, tell me more.";
+ }
+ else if (whichResponse == 1)
+ {
+ response = "Hmmm.";
+ }
+ else if (whichResponse == 2)
+ {
+ response = "Do you really think so?";
+ }
+ else if (whichResponse == 3)
+ {
+ response = "You don't say.";
+ }
+ return response;
+ }
+
+ public static void main(String[] args)
+ {
+ Magpie2 maggie = new Magpie2();
+
+ System.out.println(maggie.getGreeting());
+ System.out.println(maggie.getResponse("My mother and I talked last night."));
+ System.out.println(maggie.getResponse("I said no!"));
+ System.out.println(maggie.getResponse("The weather is nice."));
+ System.out.println(maggie.getResponse("Do you know my brother?"));
+ }
+ }
+
+.. |JuiceMind| raw:: html
+
+ JuiceMind
-You can also run a version of the |Magpie lab on repl.it| that uses the Scanner class for input so that you can type in your own input to interact with it.
+.. |replit| raw:: html
+
+ replit
+
+You can also run a version of the Magpie lab on |JuiceMind| or |replit| that uses the Scanner class for input so that you can type in your own input to interact with it.
-As you can see the ``getResponse`` method of Magpie2 looks for certain keywords like ``"mother"`` and ``"brother"``. Why do you think the response to "Do you know my brother?" isn't "Tell me more about your family."? Discuss this with partner in pairs and see if you can figure it out. See if you can modify the code above to respond correctly.
+As you can see the ``getResponse`` method of Magpie2 looks for certain keywords like ``"mother"`` and ``"brother"``. Why do you think the response to "Do you know my brother?" isn't "Tell me more about your family."? Discuss this with partner in pairs and see if you can figure it out.
The response to "The weather is nice." is one of the random responses. Look at the code to see how the ``if`` statement assigns a value to the response and returns that response.
The method ``getRandomResponse`` generates a random number and uses that to assign the response. Modify the code above to add other random responses.
+
+
Exercises
------------
@@ -132,7 +242,7 @@ Alter the code above or in your own IDE (see section below) to do the following.
* Pick three more keywords, such as “no” and “brother” and edit the ``getResponse`` method to respond to each of these.
-* What happens when more than one keyword appears in a string? Try the input “My **mother** has a **dog** but **no** cat.” Which response did you get -- was it the one about family or the one about pets or the negative one for no? Change the order of your if-else-if statements to make it so that one of the other responses is selected and try running it again.
+* What happens when more than one keyword appears in a string? Try the input ``My **mother** has a **dog** but **no** cat.`` Which response did you get -- was it the one about family or the one about pets or the negative one for no? Change the order of your if-else-if statements to make it so that one of the other responses is selected and try running it again.
.. shortanswer:: short-lab1b1
:optional:
@@ -142,9 +252,7 @@ Alter the code above or in your own IDE (see section below) to do the following.
Activity 2: Actual Code - (Optional)
-------------------------------------
-You can do all of Activity 2 with the actual code using the Scanner class for input instead if you prefer.
-
-Here is the actual code for the |Magpie lab on repl.it|. It uses the ``Scanner`` class to read input from the user. The ``Scanner`` class is not on the AP CS A exam. You can log in to repl.it and use this code and change it to do this lab.
+You can do all of Activity 2 with the actual code using the Scanner class for input instead if you prefer. The ``Scanner`` class is not on the AP CSA exam. You can use |JuiceMind| or |replit| online.
Or you can copy and paste in the code from below into any Integrated Development Environment (IDE) like DrJava or JGrasp to run on your computer.
@@ -157,29 +265,28 @@ Here is the code for MagpieRunner2.java.
/**
* 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();
- }
- }
+ /** 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.
@@ -188,71 +295,72 @@ Here is the code for Magpie2.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;
- }
- }
+ /**
+ * Get a default greeting
+ *
+ * @return a greeting
+ */
+ public String getGreeting()
+ {
+ return "Hello, let's talk.";
+ }
+
+ /**
+ * Gives a response to a user statement
+ *
+ * @param statement the user statement
+ * @return a response based on the rules given
+ */
+ public String getResponse(String statement)
+ {
+ String response = "";
+ if (statement.indexOf("no") >= 0)
+ {
+ response = "Why so negative?";
+ } else if (statement.indexOf("mother") >= 0
+ || statement.indexOf("father") >= 0
+ || statement.indexOf("sister") >= 0
+ || statement.indexOf("brother") >= 0)
+ {
+ response = "Tell me more about your family.";
+ }
+ else
+ {
+ response = getRandomResponse();
+ }
+ return response;
+ }
+
+ /**
+ * Pick a default response to use if nothing else fits.
+ *
+ * @return a non-committal string
+ */
+ private String getRandomResponse()
+ {
+ final int NUMBER_OF_RESPONSES = 4;
+ double r = Math.random();
+ int whichResponse = (int) (r * NUMBER_OF_RESPONSES);
+ String response = "";
+
+ if (whichResponse == 0)
+ {
+ response = "Interesting, tell me more.";
+ }
+ else if (whichResponse == 1)
+ {
+ response = "Hmmm.";
+ }
+ else if (whichResponse == 2)
+ {
+ response = "Do you really think so?";
+ }
+ else if (whichResponse == 3)
+ {
+ response = "You don't say.";
+ }
+
+ return response;
+ }
+ }
+
diff --git a/_sources/Unit3-If-Statements/magpie3.rst b/_sources/Unit3-If-Statements/magpie3.rst
index 6a27b1b5f..869a4c226 100644
--- a/_sources/Unit3-If-Statements/magpie3.rst
+++ b/_sources/Unit3-If-Statements/magpie3.rst
@@ -1,11 +1,13 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: lab-1c-
:start: 1
-
+
.. highlight:: java
:linenothreshold: 4
-
+|Time45|
Activity 3: Better Keyword Detection
=======================================
@@ -20,41 +22,63 @@ and ``toLowerCase`` methods. Do they do what you thought they would? The metho
.. activecode:: lc-strEx
:language: java
-
+ :autograde: unittest
+
+ Run the code below. Why do you think you might want to change the string to all lowercase characters? Why doesn't the value of ``sample`` change? Do string methods change the string? Try some other string methods.
+ ~~~~
/**
- * A program to allow students to try out different
- * String methods.
+ * 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:
-
- }
+ public static void main(String[] args)
+ {
+ String sample = "The quick brown fox jumped over the lazy dog.";
+
+ // Demonstrate the indexOf method.
+ int position = sample.indexOf("quick");
+ System.out.println("sample.indexOf(\"quick\") = " + position);
+
+ // Demonstrate the toLowerCase method.
+ String lowerCase = sample.toLowerCase();
+ System.out.println("sample.toLowerCase() = " + lowerCase);
+ System.out.println("After toLowerCase(), sample = " + sample);
+
+ // Try other methods here:
+
+ }
+ }
+
+ ====
+ // should pass if/when they run code
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "sample.indexOf(\"quick\") = 4\n...";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
}
-
+
.. |String in Java documentation| raw:: html
String in Java documentation|
-
+
Open the API for |String in Java documentation| in another tab. Scroll down to the Method Summary section and find the
-``indexOf(String str)`` method. Follow the link and read the description of the ``indexOf`` method.
+``indexOf(String str)`` method. Follow the link and read the description of the ``indexOf`` method.
.. fillintheblank:: fill-lab1b1
@@ -63,8 +87,8 @@ Open the API for |String in Java documentation| in another tab. Scroll down to t
- :-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:
@@ -72,293 +96,304 @@ specified:
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 ``}``.
+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;
- }
-
-.. |repl.it version 3| raw:: html
-
- repl.it version 3
-
-Run the code below or this |repl.it version 3| to see this new method findKeyWord in action.
-
-Try replacing the call in main at line 178 below 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);``
-
-You can also step through the code in the |Java Visualizer|. It may take a minute or two to load. Click the forward button at the bottom of the code to execute the next statement.
-
+
+ private int findKeyword(String statement, String goal,
+ int startPos)
+ {
+ String phrase = statement.trim();
+ // The only change to incorporate the startPos is in
+ // the line below
+ int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(),
+ startPos);
+
+ // Refinement--make sure the goal isn't part of a word
+ while (psn >= 0)
+ {
+ // Find the string of length 1 before and after
+ // the word
+ String before = " ", after = " ";
+ if (psn > 0)
+ {
+ before = phrase.substring(psn - 1, psn).toLowerCase();
+ }
+ if (psn + goal.length() < phrase.length())
+ {
+ after = phrase.substring(
+ psn + goal.length(),
+ psn + goal.length() + 1)
+ .toLowerCase();
+ }
+
+ /* determine the values of psn, before, and after at this point */
+
+ // If before and after aren't letters, we've
+ // found the word
+ if (((before.compareTo("a") < 0) ||
+ (before.compareTo("z") > 0)) // before is not a letter
+ && ((after.compareTo("a") < 0) ||
+ (after.compareTo("z") > 0)))
+ {
+ return psn;
+ }
+
+ // The last position didn't work, so let's find
+ // the next, if there is one.
+ psn = phrase.indexOf(goal.toLowerCase(),psn + 1);
+
+ }
+
+ return -1;
+ }
+
+.. |JuiceMind| raw:: html
+
+ JuiceMind
+
+.. |replit.com version 3| raw:: html
+
+ replit.com version 3
+
+Run the code below or |JuiceMind| or |replit.com version 3| to see this new method ``findKeyword`` in action. It is called from the ``getResponse`` method to print out an appropriate response based on a keyword. For example, looking for the word ``"no"`` to print out ``"Why so negative?"``, but it won't match no inside of another word like ``"another"``.
+
+.. code-block:: java
+
+ if (findKeyword(statement, "no") >= 0)
+ {
+ response = "Why so negative?";
+ }
+
+You can also step through the code in the |Java Visualizer| or using the CodeLens button below. It may take a minute or two to load. Click the forward button at the bottom of the code to execute the next statement.
+
.. |Magpie Chatbot Lab| raw:: html
Magpie Chatbot Lab
-
-Modify the code below to print the values of ``psn``, ``before``, and ``after`` right after the comment on line 100 in the ``findKeyword`` method below. Record each of the values in a table. The College Board student guide for the |Magpie Chatbot Lab| has a table on page 8 that can be printed.
+
+
.. activecode:: lc-magpie3
:language: java
+ :autograde: unittest
+ Modify the code below to print the values of ``psn``, ``before``, and ``after`` right after the comment on line 100 in the ``findKeyword`` method below. Record each of the values in a table. The College Board student guide for the |Magpie Chatbot Lab| has a table on page 8 that can be printed. Use the CodeLens button to step through the code.
+ ~~~~
/**
- * A program to carry on conversations with a human user.
- * This version:
- *
+
+
+
+
+
+.. poll:: most-common-posttest-unlucky
+ :option_1: A
+ :option_2: B
+ :option_3: C
+ :option_4: D
+ :results: instructor
+
+ Unlucky Number
+
+
+
+
+.. activecode:: most-common-posttest-work
+ :language: java
+ :autograde: unittest
+ :nocodelens:
+
+ .. raw:: html
+
+ Working Overtime
+
+
+ You and your project partner are deciding whether to work overtime based on your remaining workload. The parameter ``yourWorkload`` represents how much work you have left, and ``partnerWorkload`` represents how much work your project partner has left, both in the range from 0 to 20. The result is an ``int`` value indicating whether you both should work overtime. Return:
+ * If either workload is 5 or less (i.e., there's little work left), return 0 (no need to work overtime);
+ * With the exception that if eithr workload is 18 or more, return 2 (i.e., a large amount of work to complete);
+ * Otherwise, return 1 (maybe).
+
+ .. table::
+ :name: work-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``needOvertime(4, 3)`` | ``0`` |
+ +----------------------------------------------------+-----------------+
+ | ``needOvertime(4, 18)`` | ``2`` |
+ +----------------------------------------------------+-----------------+
+ | ``needOvertime(6, 15)`` | ``1`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+ public class OvertimeDecision
+ {
+ public static int needOvertime(int yourWorkload, int partnerWorkload)
+ {
+ // Your Code Here //
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(needOvertime(4, 3)); // Output: 0
+
+ System.out.println(needOvertime(4, 18)); // Output: 2
+
+ System.out.println(needOvertime(6, 15)); // Output: 1
+
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testValue1() throws IOException {
+ OvertimeDecision c = new OvertimeDecision();
+ assertTrue(getResults(0, c.needOvertime(4, 3), "needOvertime(4, 3)"));
+ }
+
+ @Test
+ public void testValue2() throws IOException {
+ OvertimeDecision c = new OvertimeDecision();
+ assertTrue(getResults(2, c.needOvertime(4, 18), "needOvertime(4, 18)"));
+ }
+
+ @Test
+ public void testValue3() throws IOException {
+ OvertimeDecision c = new OvertimeDecision();
+ assertTrue(getResults(1, c.needOvertime(6, 15), "needOvertime(6, 15)"));
+ }
+
+ @Test
+ public void testValue4() throws IOException {
+ OvertimeDecision c = new OvertimeDecision();
+ assertTrue(getResults(1, c.needOvertime(10, 15), "Hidden test"));
+ }
+
+ @Test
+ public void testValue5() throws IOException {
+ OvertimeDecision c = new OvertimeDecision();
+ assertTrue(getResults(2, c.needOvertime(18, 3), "Hidden test"));
+ }
+ }
+
+
diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst
new file mode 100644
index 000000000..c357b70bc
--- /dev/null
+++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P-lib.rst
@@ -0,0 +1,181 @@
+Practice Problems (Mixed Code)
+==============================
+
+.. parsonsprob:: most-common-practice-alarmclock-mixed
+ :numbered: left
+ :adaptive:
+ :noindent:
+
+
+ Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``.
+
+ .. table::
+ :name: alarmClock-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``alarmClock(1, false)`` | ``7:00`` |
+ +----------------------------------------------------+-----------------+
+ | ``alarmClock(5, false)`` | ``7:00`` |
+ +----------------------------------------------------+-----------------+
+ | ``alarmClock(0, false)`` | ``10:00`` |
+ +----------------------------------------------------+-----------------+
+
+ -----
+ public class VacayAlarmClock {
+ public static String alarmClock(int day, boolean vacation) {
+ =====
+ if (day >= 1 && day <= 5 && (vacation == false)){
+ =====
+ return "7:00";
+ =====
+ } else if ((day == 0 || day == 6 && (vacation == false)) || (day >= 1 && day <= 5 && (vacation == true))){
+ =====
+ return "10:00";
+ =====
+ } else {
+ =====
+ return "off";
+ =====
+ }
+ }
+ }
+
+
+.. parsonsprob:: most-common-practice-datefashion-mixed
+ :numbered: left
+ :adaptive:
+ :noindent:
+
+ You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe).
+
+ .. table::
+ :name: datFashion-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``dateFashion(5, 10)`` | ``2`` |
+ +----------------------------------------------------+-----------------+
+ | ``dateFashion(8, 2)`` | ``0`` |
+ +----------------------------------------------------+-----------------+
+ | ``dateFashion(5, 5)`` | ``1`` |
+ +----------------------------------------------------+-----------------+
+ -----
+ public class DateStylishness {
+ =====
+ public static int dateFashion(int you, int date) {
+ =====
+ if (you <= 2 || date <= 2) {
+ =====
+ return 0; }
+ =====
+ if (you >= 8 || date >= 8) {
+ =====
+ return 2; }
+ =====
+ return 1; }
+ =====
+ }
+
+
+.. parsonsprob:: most-common-practice-frontback-mixed
+ :numbered: left
+ :grader: dag
+ :noindent:
+
+ Create the method ``front_back(str, start, end)`` that takes three strings and returns
+ a string based on the following conditions.
+
+ * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``.
+ * If ``str`` contains ``start`` at the beginning of the string return ``"s"``.
+ * if ``str`` contains ``end`` at the end of the string return ``"e"``.
+ * Otherwise return ``"n"``.
+
+ .. table::
+ :name: front-back-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Closed", "Open", "noon")`` | ``"n"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` |
+ +----------------------------------------------------+-----------------+
+
+ -----
+ public class FrontBack { #tag:0; depends:;
+ =====
+ public static String front_back(String str, String start, String end) { #tag:1; depends:0;
+ =====
+ Boolean beginWithStart = str.indexOf(start) == 0;
+ Boolean endWithEnd = str.indexOf(end) == (str.length() - end.length()); #tag:2; depends:1;
+ =====
+ if (beginWithStart && endWithEnd) { #tag:3; depends:2;
+ =====
+ return "s_e"; } #tag:4; depends:3;
+ =====
+ else if (beginWithStart && !endWithEnd) {
+ return "s";} #tag:5; depends:4;
+ =====
+ else if (!beginWithStart && endWithEnd) {
+ return "e";} #tag:6; depends:4;
+ =====
+ else { #tag:7; depends:5,6;
+ =====
+ return "n"; #tag:8; depends:7;
+ =====
+ } #tag:9; depends:8;
+ =====
+ } #tag:10; depends:9;
+ =====
+ } #tag:11; depends:10;
+
+
+.. image:: Figures/experiment/pretest-gym1.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/pretest-gym2.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/pretest-lucky-1.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/pretest-lucky-2.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/posttest-theme1.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/posttest-theme2.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/posttest-unlucky-1.png
+ :width: 0
+ :align: left
+
+.. image:: Figures/experiment/posttest-unlucky-2.png
+ :width: 0
+ :align: left
\ No newline at end of file
diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst
new file mode 100644
index 000000000..1c24efb0e
--- /dev/null
+++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-P.rst
@@ -0,0 +1,35 @@
+.. qnum::
+ :prefix: exp-2-
+ :start: 1
+
+Practice Problems (Mixed Code Help)
+==============================
+
+.. selectquestion:: most-common-practice-alarmclock-toggle
+ :fromid: most-common-practice-alarmclock-written, most-common-practice-alarmclock-mixed
+ :toggle: lock
+
+.. selectquestion:: most-common-practice-datefashion-toggle
+ :fromid: most-common-practice-datefashion-written, most-common-practice-datefashion-mixed
+ :toggle: lock
+
+.. selectquestion:: most-common-practice-frontback-toggle
+ :fromid: most-common-practice-frontback-written, most-common-practice-frontback-mixed
+ :toggle: lock
+
+.. raw:: html
+
+ click on the following link to proceed to the posttest: posttest
+ +.. raw:: html + + \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst new file mode 100644 index 000000000..d98da5823 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice-W.rst @@ -0,0 +1,230 @@ +.. qnum:: + :prefix: exp-3- + :start: 1 + +Practice Problems (Write Code) +============================== + +.. activecode:: most-common-practice-alarmclock-written + :language: java + :autograde: unittest + :nocodelens: + + Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``. + + .. table:: + :name: alarmClock-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``alarmClock(1, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(5, false)`` | ``7:00`` | + +----------------------------------------------------+-----------------+ + | ``alarmClock(0, false)`` | ``10:00`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class VacayAlarmClock + { + public static String alarmClock(int day, boolean vacation) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(alarmClock(1, false)); + System.out.println(alarmClock(5, false)); + System.out.println(alarmClock(0, false)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "7:00, 7:00, 10:00"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + + +.. activecode:: most-common-practice-datefashion-written + :language: java + :autograde: unittest + :nocodelens: + + You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe). + + .. table:: + :name: datFashion-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``dateFashion(5, 10)`` | ``2`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(8, 2)`` | ``0`` | + +----------------------------------------------------+-----------------+ + | ``dateFashion(5, 5)`` | ``1`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class DateStylishness + { + public static int dateFashion(int you, int date) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + System.out.println(dateFashion(5, 10)); + System.out.println(dateFashion(8, 2)); + System.out.println(dateFashion(5, 5)); + } + } + + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "2, 0, 1"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + + } + + + } + +.. activecode:: most-common-practice-frontback-written + :language: java + :autograde: unittest + :nocodelens: + + Create the method ``front_back(str, start, end)`` that takes three strings and returns + a string based on the following conditions. + + * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``. + * If ``str`` contains ``start`` at the beginning of the string return ``"s"``. + * if ``str`` contains ``end`` at the end of the string return ``"e"``. + * Otherwise return ``"n"``. + + .. table:: + :name: front-back-table + :class: longtable + :align: left + :width: 80% + + +----------------------------------------------------+-----------------+ + | Example Input | Expected Output | + +====================================================+=================+ + | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("Closed", "Open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` | + +----------------------------------------------------+-----------------+ + + ~~~~ + public class FrontBack + { + public static String front_back(String str, String start, String end) + { + // ADD CODE HERE // + } + + public static void main(String[] args) + { + String str1 = "Opening time"; + String start1 = "Open"; + String end1 = "noon"; + System.out.println(front_back(str1, start1, end1)); + + String str2 = "Afternoon"; + String start2 = "Open"; + String end2 = "noon"; + System.out.println(front_back(str2, start2, end2)); + + String str3 = "Open at noon"; + String start3 = "Open"; + String end3 = "noon"; + System.out.println(front_back(str3, start3, end3)); + } + } + + ==== + import static org.junit.Assert.*; + import org.junit.Test; + import java.io.IOException; + import java.util.Arrays; + + public class RunestoneTests extends CodeTestHelper { + public RunestoneTests() { + super(); + } + + @Test + public void testBoundarySum() throws IOException { + String output = getMethodOutput("main"); + String expect = "s\ne\ns_e\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + } + + +.. raw:: html + +click on the following link to proceed to the posttest: posttest
+ +.. raw:: html + + \ No newline at end of file diff --git a/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst new file mode 100644 index 000000000..61bd32483 --- /dev/null +++ b/_sources/Unit3-If-Statements/topic-3-13-experiment-practice.rst @@ -0,0 +1,63 @@ +.. qnum:: + :prefix: exp-4- + :start: 1 + +Practice Problems +============================ + + +.. raw:: html + +age is the person's age in years, and visitsPerWeek is the average number of visits per week. The result is the discount percentage encoded as an int. The conditions are:
+
+
+
+
+
+
+.. poll:: most-common-pretest-lucky
+ :option_1: A
+ :option_2: B
+ :option_3: C
+ :option_4: D
+ :results: instructor
+
+ Lucky Number
+ day and hour. The day is the day of birth (from 1 to 31), and the hour is the hour of birth (from 0 to 23). According to her, the lucky number is calculated as follows:
+
+
+
+
+
+
+
+
+
+.. activecode:: most-common-pretest-clean
+ :language: java
+ :autograde: unittest
+ :nocodelens:
+
+ .. raw:: html
+
+ Apartment Cleaning
+
+ You and your roommate are deciding whether to clean the apartment. The parameter ``yourMessiness`` represents how messy your side of the apartment is, and ``roommateMessiness`` represents how messy your roommate's side is, both in the range from 0 to 20. The result is an ``int`` value indicating whether it's time to clean. Return:
+ * If either messiness is 5 or less (i.e., it's still relatively clean), return 0 (no need to clean);
+ * With the exception that if either messiness is 18 or more (i.e. the apartment is very messy), return 2 (definitely needs to clean);
+ * Otherwise, return 1 (maybe).
+
+ .. table::
+ :name: clean-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``shouldClean(4, 3)`` | ``0`` |
+ +----------------------------------------------------+-----------------+
+ | ``shouldClean(4, 18)`` | ``2`` |
+ +----------------------------------------------------+-----------------+
+ | ``shouldClean(6, 15)`` | ``1`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+ public class CleaningDecision
+ {
+ public static int shouldClean(int yourMessiness, int roommateMessiness)
+ {
+ // Your Code Here //
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(shouldClean(4, 3)); // Output: 0
+
+ System.out.println(shouldClean(4, 18)); // Output: 2
+
+ System.out.println(shouldClean(6, 15)); // Output: 1
+
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testValue1() throws IOException {
+ CleaningDecision c = new CleaningDecision();
+ assertTrue(getResults(0, c.shouldClean(4, 3), "shouldClean(4, 3)"));
+ }
+
+ @Test
+ public void testValue2() throws IOException {
+ CleaningDecision c = new CleaningDecision();
+ assertTrue(getResults(2, c.shouldClean(4, 18), "shouldClean(4, 18)"));
+ }
+
+ @Test
+ public void testValue3() throws IOException {
+ CleaningDecision c = new CleaningDecision();
+ assertTrue(getResults(1, c.shouldClean(6, 15), "shouldClean(6, 15)"));
+ }
+
+ @Test
+ public void testValue4() throws IOException {
+ CleaningDecision c = new CleaningDecision();
+ assertTrue(getResults(1, c.shouldClean(10, 15), "Hidden test"));
+ }
+
+ @Test
+ public void testValue5() throws IOException {
+ CleaningDecision c = new CleaningDecision();
+ assertTrue(getResults(2, c.shouldClean(18, 3), "Hidden test"));
+ }
+ }
diff --git a/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst b/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst
new file mode 100644
index 000000000..63d798066
--- /dev/null
+++ b/_sources/Unit3-If-Statements/topic-3-13-more-practice-coding.rst
@@ -0,0 +1,283 @@
+.. qnum::
+ :prefix: 3-13-
+ :start: 1
+
+FRQ Style Coding Practice
+==============================
+
+In the following exercises which are similar to the Free Response Questions (FRQs) in the AP exam, you will write code inside a method with parameters and return values. Make sure that you use the parameter variables given in the method header and return a value.
+
+.. code-block:: java
+
+ public static return-type method-name(param-type param-var1, param-type param-var2, ...)
+ {
+ // ADD CODE HERE using the param-variables //
+ return result;
+ }
+
+
+.. activecode:: front_back_written
+ :language: java
+ :autograde: unittest
+
+ Create the method ``front_back(str, start, end)`` that takes three strings and returns
+ a string based on the following conditions.
+
+ * If ``str`` contains ``start`` at the beginning and ``end`` at the end then return ``"s_e"``.
+ * If ``str`` contains ``start`` at the beginning of the string return ``"s"``.
+ * if ``str`` contains ``end`` at the end of the string return ``"e"``.
+ * Otherwise return ``"n"``.
+
+ .. table::
+ :name: front-back-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``front_back("Open at noon", "Open", "noon")`` | ``"s_e"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Opening time", "Open", "noon")`` | ``"s"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Afternoon", "Open", "noon")`` | ``"e"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("Closed", "Open", "noon")`` | ``"n"`` |
+ +----------------------------------------------------+-----------------+
+ | ``front_back("It is noon now", "open", "noon")`` | ``"n"`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+ public class FrontBack
+ {
+ public static String front_back(String str, String start, String end)
+ {
+ // ADD CODE HERE //
+ }
+
+ public static void main(String[] args)
+ {
+ String str1 = "Opening time";
+ String start1 = "Open";
+ String end1 = "noon";
+ System.out.println(front_back(str1, start1, end1));
+
+ String str2 = "Afternoon";
+ String start2 = "Open";
+ String end2 = "noon";
+ System.out.println(front_back(str2, start2, end2));
+
+ String str3 = "Open at noon";
+ String start3 = "Open";
+ String end3 = "noon";
+ System.out.println(front_back(str3, start3, end3));
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testBoundarySum() throws IOException {
+ String output = getMethodOutput("main");
+ String expect = "s\ne\ns_e\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
+
+
+.. activecode:: squirrelPlay_written
+ :language: java
+ :autograde: unittest
+
+ The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an ``int temperature`` and a ``boolean isSummer``, return ``true`` if the squirrels play and ``false`` otherwise.
+
+ .. table::
+ :name: squirrelPlay-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``squirrelPlay(70, false)`` | ``true`` |
+ +----------------------------------------------------+-----------------+
+ | ``squirrelPlay(95, false)`` | ``false`` |
+ +----------------------------------------------------+-----------------+
+ | ``squirrelPlay(95, true)`` | ``true`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+
+ public class SquirrelParty
+ {
+ public static boolean squirrelPlay(int temp, boolean isSummer)
+ {
+ // ADD CODE HERE //
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(squirrelPlay(70, false));
+ System.out.println(squirrelPlay(95, false));
+ System.out.println(squirrelPlay(95, true));
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testBoundarySum() throws IOException {
+ String output = getMethodOutput("main");
+ String expect = "true, false, true";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+
+ }
+
+
+ }
+
+.. activecode:: alarmClock_written
+ :language: java
+ :autograde: unittest
+
+ Given a ``day`` of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a ``boolean`` indicating if we are on ``vacation``, return a string of the form ``"7:00"`` indicating when the alarm clock should ring. Weekdays, the alarm should be ``"7:00"`` and on the weekend it should be ``"10:00"``. Unless we are on vacation -- then on weekdays it should be ``"10:00"`` and weekends it should be ``"off"``.
+
+ .. table::
+ :name: alarmClock-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``alarmClock(1, false)`` | ``7:00`` |
+ +----------------------------------------------------+-----------------+
+ | ``alarmClock(5, false)`` | ``7:00`` |
+ +----------------------------------------------------+-----------------+
+ | ``alarmClock(0, false)`` | ``10:00`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+ public class VacayAlarmClock
+ {
+ public static String alarmClock(int day, boolean vacation)
+ {
+ // ADD CODE HERE //
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(alarmClock(1, false));
+ System.out.println(alarmClock(5, false));
+ System.out.println(alarmClock(0, false));
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testBoundarySum() throws IOException {
+ String output = getMethodOutput("main");
+ String expect = "7:00, 7:00, 10:00";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+
+ }
+
+
+ }
+
+
+.. activecode:: dateFashion_written
+ :language: java
+ :autograde: unittest
+
+ You and your date are trying to get a table at a restaurant. The parameter ``you`` is the stylishness of your clothes, in the range 0..10, and ``date`` is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is ``2`` (yes). With the exception that if either of you has style of 2 or less, then the result is ``0`` (no). Otherwise the result is ``1`` (maybe).
+
+ .. table::
+ :name: datFashion-table
+ :class: longtable
+ :align: left
+ :width: 80%
+
+ +----------------------------------------------------+-----------------+
+ | Example Input | Expected Output |
+ +====================================================+=================+
+ | ``dateFashion(5, 10)`` | ``2`` |
+ +----------------------------------------------------+-----------------+
+ | ``dateFashion(8, 2)`` | ``0`` |
+ +----------------------------------------------------+-----------------+
+ | ``dateFashion(5, 5)`` | ``1`` |
+ +----------------------------------------------------+-----------------+
+
+ ~~~~
+ public class DateStylishness
+ {
+ public static int dateFashion(int you, int date)
+ {
+ // ADD CODE HERE //
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println(dateFashion(5, 10));
+ System.out.println(dateFashion(8, 2));
+ System.out.println(dateFashion(5, 5));
+ }
+ }
+
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.Test;
+ import java.io.IOException;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper {
+ public RunestoneTests() {
+ super();
+ }
+
+ @Test
+ public void testBoundarySum() throws IOException {
+ String output = getMethodOutput("main");
+ String expect = "2, 0, 1";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+
+ }
+
+
+ }
diff --git a/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst b/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst
new file mode 100644
index 000000000..3ce7daac5
--- /dev/null
+++ b/_sources/Unit3-If-Statements/topic-3-13-more-practice-experiment.rst
@@ -0,0 +1,28 @@
+More Practice (Experiment)
+===========================
+
+Thank you for taking part in this study! We are researchers who are trying to improve the teaching and learning of programming.
+
+*If your teacher is asking you to do this experiment, please wait until your teacher instructs you to complete a section. Do not start it on your own.*
+
+This study has three parts. It will take approximately 45 minutes in total to complete the study.
+Please do the parts in order following your teacher's instruction, and answer questions to the best of your ability without any outside help, and please do not discuss with others. You can stop working on a problem after you worked on it for about five minutes without solving it.
+If you have questions about this study please email Dr. Barbara Ericson at barbarer@umich.edu.
+
+The three parts are:
+
+* 1. Pre Test - Questions that measure your knowledge prior to doing the practice problems.
+
+* 2. Practice - Practice problems. You are going to be randomly assigned to one condition. After you open this page, please finish all problems in one session, otherwise you might lose your progress.
+
+* 3. Post Test - Post test problems that measure your knowledge after doing the practice problems.
+
+Based on your teacher's plan, you might do all three parts in one class, or do part 1 at the end of one class and part 2 & 3 at the beginning of the next class.
+
+
+.. toctree::
+ :maxdepth: 3
+
+ topic-3-13-experiment-pretest.rst
+ topic-3-13-experiment-practice.rst
+ topic-3-13-experiment-posttest.rst
diff --git a/_sources/Unit3-If-Statements/topic-3-2-ifs.rst b/_sources/Unit3-If-Statements/topic-3-2-ifs.rst
index b5f0b45f2..3511960a9 100644
--- a/_sources/Unit3-If-Statements/topic-3-2-ifs.rst
+++ b/_sources/Unit3-If-Statements/topic-3-2-ifs.rst
@@ -1,33 +1,19 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 3-2-
:start: 1
-
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+
+
+|Time45|
if Statements and Control Flow
===============================
-.. index::
- single: conditional
- single: if
- pair: conditional; if
+.. index::
+ single: conditional
+ single: if
+ pair: conditional; if
If you took an AP CSP course or used a block programming language like Scratch, you've probably seen if blocks or statements before. *If statements* are found in all programming languages as a way to make choices. Here's a comparison of ifs in App Inventor blocks, AP CSP block and pseudocode and Java ifs.
@@ -46,7 +32,7 @@ The statements in a Java main method normally run or execute one at a time in th
:figclass: align-center
Figure 2: The order that statements execute in a conditional
-
+
A conditional uses the keyword ``if`` followed by Boolean expression inside of an open parenthesis ``(`` and a close parenthesis ``)`` and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. The open curly brace ``{`` and a close curly brace ``}`` are used to group a block of statements together. It is recommended to always put in the curly braces even if you have just one statement under the if statement. The questions you will see on the AP exam will use curly braces.
@@ -57,11 +43,11 @@ A conditional uses the keyword ``if`` followed by Boolean expression inside of
if (boolean expression)
Do statement;
// Or a single if with {}
- if (boolean expression)
+ if (boolean expression)
{
Do statement;
}
- // A block if statement: { } required
+ // A block if statement: { } required
if (boolean expression)
{
Do Statement1;
@@ -72,47 +58,47 @@ A conditional uses the keyword ``if`` followed by Boolean expression inside of
.. note::
- Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition.
-
-Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere).
+ Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition.
+
+Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere).
.. activecode:: lccb1
:language: java
:autograde: unittest
-
+
The variable ``isRaining`` is a boolean variable that is either true or false. If it is true then the message ``Take an umbrella!`` will be printed and then execution will continue with the next statement which will print ``Drive carefully``. Run the code below to see this.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- boolean isRaining = true;
- if (isRaining)
- {
- System.out.println("Take an umbrella!");
- }
- System.out.println("Drive carefully");
- }
+ public static void main(String[] args)
+ {
+ boolean isRaining = true;
+ if (isRaining)
+ {
+ System.out.println("Take an umbrella!");
+ }
+ System.out.println("Drive carefully");
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Take an umbrella! \nDrive carefully";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
-
+ import org.junit.*;
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Take an umbrella! \nDrive carefully";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
|Exercise| **Check your understanding**
@@ -122,12 +108,12 @@ Imagine that your cell phone wanted to remind you to take an umbrella if it was
- :^Drive carefully$: Correct. If the boolean is false, it will skip executing the print statement after the if.
:.*: Try it and see
-
+
Relational Operators in If Statements
---------------------------------------
-Most if statements have a boolean condition that uses relational operators like ==, !=, <, >, <=, >=, as we saw in the last lesson.
+Most if statements have a boolean condition that uses relational operators like ==, !=, <, >, <=, >=, as we saw in the last lesson.
|CodingEx| **Coding Exercise**
@@ -138,109 +124,170 @@ Most if statements have a boolean condition that uses relational operators like
:language: java
:autograde: unittest
:practice: T
-
+
Run the following active code a couple times until you see all the possible outputs. It prints out whether a random number is positive or equal to 0. Add another if statement that tests if it is a negative number.
~~~~
public class TestNumbers
{
- public static void main(String[] args)
- {
- // Get a random number from -10 up to 10.
- int number = (int) (Math.random()*21 - 10);
- System.out.println("The number is " + number);
-
- // is it positive?
- if (number > 0)
- {
- System.out.println(number + " is positive!");
- }
- // is it 0?
- if (number == 0)
- {
- System.out.println(number + " is zero!");
- }
- }
+ public static void main(String[] args)
+ {
+ // Get a random number from -10 up to 10.
+ int number = (int) (Math.random() * 21) - 10;
+ System.out.println("The number is " + number);
+
+ // is it positive?
+ if (number > 0)
+ {
+ System.out.println(number + " is positive!");
+ }
+ // is it 0?
+ if (number == 0)
+ {
+ System.out.println(number + " is zero!");
+ }
+ // is it negative?
+ // Add another if statement
+
+ }
}
+
====
// Test Code for Lesson 3.2.1 - Activity 1 - if-relational
- import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
-
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testPositive()
- {
- String output = "";
- int num = -999;
-
- while(num <= 0) {
- output = getMethodOutput("main");
- num = getNumber(output);
- }
-
- String expect = "The number is " + num + "\n" + num + " is positive!";
-
- boolean passed = getResults(expect, output, "Testing positive numbers");
- assertTrue(passed);
- }
-
- @Test
- public void testZero()
- {
- String output = "";
- int num = -999;
-
- while(num != 0) {
- output = getMethodOutput("main");
- num = getNumber(output);
- }
-
- String expect = "The number is " + num + "\n" + num + " is zero!";
-
- boolean passed = getResults(expect, output, "Testing zero");
- assertTrue(passed);
- }
-
- @Test
- public void testNegative()
- {
- String output = "";
- int num = 999;
-
- while(num >= 0) {
- output = getMethodOutput("main");
- num = getNumber(output);
- }
-
- String expect = "The number is " + num + "\n" + num + " is negative!";
-
- boolean passed = getResults(expect, output,"Testing negative numbers");
- assertTrue(passed);
- }
-
- private int getNumber(String output) {
- output = output.replaceAll("The number is ", "");
- int space = output.indexOf("\n");
+ import static org.junit.Assert.*;
- String numStr = output;
+ import org.junit.Test;
- if (space >= 0)
- numStr = numStr.substring(0, space).trim();
+ import java.io.*;
+ import java.util.regex.MatchResult;
+ import java.util.regex.Pattern;
- return Integer.parseInt(numStr);
- }
- }
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testPositive()
+ {
+ String output = "";
+ int num = -999, count = 0;
+
+ while (num <= 0 && count < 50)
+ {
+ output = getMethodOutput("main");
+ num = getNumber(output);
+ count++;
+
+ if (num == 9999999)
+ {
+ getResults(
+ "The number is ##\n## is positive!",
+ output,
+ "Did you forget to print the number?",
+ false);
+ assertTrue(false);
+ return;
+ }
+ }
+
+ String expect = "The number is " + num + "\n" + num + " is positive!";
+
+ boolean passed = output.contains("positive");
+ getResults(expect, output, "Testing positive numbers", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testZero()
+ {
+ String output = "";
+ int num = -999, count = 0;
+
+ while (num != 0 && count < 50)
+ {
+ output = getMethodOutput("main");
+ num = getNumber(output);
+ count++;
+
+ if (num == 9999999)
+ {
+ getResults(
+ "The number is ##\n## is zero!",
+ output,
+ "Did you forget to print the number?",
+ false);
+ assertTrue(false);
+ return;
+ }
+ }
+
+ String expect = "The number is " + num + "\n" + num + " is zero!";
+
+ boolean passed = output.contains("zero");
+ getResults(expect, output, "Testing zero", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testNegative()
+ {
+ String output = "";
+ int num = 999, count = 0;
+
+ while (num >= 0 && count < 50)
+ {
+ output = getMethodOutput("main");
+ num = getNumber(output);
+ count++;
+
+ if (num == 9999999)
+ {
+ getResults(
+ "The number is ##\n## is negative!",
+ output,
+ "Did you forget to print the number?",
+ false);
+ assertTrue(false);
+ return;
+ }
+ }
+
+ String expect = "The number is " + num + "\n" + num + " is negative!";
+
+ boolean passed = output.contains("negative");
+ getResults(expect, output, "Testing negative numbers", passed);
+ assertTrue(passed);
+ }
+
+ private int getNumber(String output)
+ {
+ String regex = "[0-9]+";
+
+ String[] matches =
+ Pattern.compile(regex)
+ .matcher(output)
+ .results()
+ .map(MatchResult::group)
+ .toArray(String[]::new);
+
+ int num = 9999999;
+
+ if (matches.length > 0)
+ {
+ num = Integer.parseInt(matches[0]);
+ }
+
+ if (output.contains("-"))
+ {
+ num *= -1;
+ }
+
+ return num;
+ }
+ }
.. note::
A common mistake in if statements is using = instead of == in the condition by mistake. You should always **use ==**, not =, in the condition of an if statement to test a variable. One equal sign (=) assigns a value to a variable, and two equal signs (==) test if a variable has a certain value.
-
+
|Exercise| **Check your understanding**
.. mchoice:: qcb1_2
@@ -252,91 +299,94 @@ Most if statements have a boolean condition that uses relational operators like
:answer_e: The code will not compile
:correct: c
:feedback_a: x is changed by the if statements.
- :feedback_b: What happens when x is greater than 2 and then greater than 4? Do both if statements.
- :feedback_c: If x is greater than 2, it's always doubled, and then that result is always greater than 4, so it's set to 0 in the second if statement.
+ :feedback_b: What happens when x is greater than 2 and then greater than 4? Do both if statements.
+ :feedback_c: If x is greater than 2, it's always doubled, and then that result is always greater than 4, so it's set to 0 in the second if statement.
:feedback_d: x is changed by the if statements.
:feedback_e: This code will compile.
Consider the following code segment. What is printed as a result of executing the code segment?
-
+
.. code-block:: java
int x = 3;
- if (x > 2)
+ if (x > 2)
{
x = x * 2;
}
- if (x > 4)
+ if (x > 4)
{
x = 0;
}
System.out.print(x);
-
+
.. More practice with if == and < > Active code.
Note always use == not = in an if statement! Test not assign.
-
+
Common Errors with If Statements
---------------------------------
Here are some rules to follow with if statements to avoid some common errors:
- - Always use curly brackets ``{`` and ``}`` to enclose the block of statements under the if condition. Java doesn't care if you indent the code -- it goes by the { }.
-
- - Don't put in a semicolon ``;`` after the first line of the if statement, if (test);. The if statement is a multiline block of code that starts with the if condition and then { the body of the if statement }.
-
- - Always use **==**, not =, in the condition of an if statement to test a variable. One = assigns, two == tests!
+ - Always use curly braces (``{`` and ``}``) to enclose the block of statements under the if condition. Java doesn't care if you indent the code—it goes by the ``{ }``.
+
+ - Don't put in a semicolon ``;`` after the first line of the if statement, ``if (test);``. The ``if`` statement is a multiline block of code that starts with the ``if`` condition and then ``{`` the body of the if statement ``}``.
+
+ - Always use ``==``, not ``=``, in the condition of an if statement to test a variable. One ``=`` assigns, two ``==`` tests!
|CodingEx| **Coding Exercise**
-
+
.. activecode:: lccb2-indent
:language: java
:autograde: unittest
:practice: T
- The code below doesn't work as expected. Fix it to only print "Wear a coat" and "Wear gloves" when isCold is true.
+ The code below doesn't work as expected. Fix it to only print ``Wear a coat`` and ``Wear gloves`` when isCold is true.
~~~~
- public class Test
+ public class Test1
{
- public static void main(String[] args)
- {
- boolean isCold = false;
- if (isCold = true);
- System.out.println("Wear a coat");
- System.out.println("Wear gloves");
-
- }
+ public static void main(String[] args)
+ {
+ boolean isCold = false;
+ if (isCold = true);
+ System.out.println("Wear a coat");
+ System.out.println("Wear gloves");
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "";
- boolean passed = getResults(expect, output, "Expected output from main if isCold is false");
- assertTrue(passed);
- }
- @Test
- public void testCountCurlies()
- {
- String code = getCode();
- int num = countOccurences(code, "{");
- boolean passed = num >= 3;
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "";
+ boolean passed = getResults(expect, output, "Expected output from main if isCold is false");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCountCurlies()
+ {
+ String code = getCode();
+ int num = countOccurences(code, "{");
+ boolean passed = num >= 3;
+
+ getResults("3", "" + num, "Number of {", passed);
+ assertTrue(passed);
+ }
+ }
- getResults("3", "" + num, "Number of {", passed);
- assertTrue(passed);
- }
- }
-
|Groupwork| Programming Challenge : Magic 8 Ball
------------------------------------------------
@@ -344,121 +394,133 @@ Here are some rules to follow with if statements to avoid some common errors:
:width: 100
:align: left
:alt: Magic 8 Ball
-
-
-.. |video| raw:: html
- video
+
+.. |simulator| raw:: html
+
+ simulator
.. |lesson 2.9| raw:: html
lesson 2.9
-
-Have you ever seen a Magic 8 ball? You ask it a yes-no question and then shake it to get a random response like "Signs point to yes!", "Very doubtful", etc. If you've never seen a Magic 8 ball, check out this |video|.
+
+Have you ever seen a Magic 8 ball? You ask it a yes-no question and then shake it to get a random response like ``Signs point to yes!``, ``Very doubtful``, etc. If you've never seen a Magic 8 ball, check out this |simulator|.
We encourage you to work in pairs for this challenge. Come up with 8 responses to yes-no questions. Write a program below that chooses a random number from 1 to 8 and then uses if statements to test the number and print out the associated random response from 1-8. If you need help with random numbers, see |lesson 2.9|.
.. activecode:: challenge3-2-if-Magic8ball
:language: java
:autograde: unittest
-
+
public class Magic8Ball
{
- public static void main(String[] args)
- {
- // Get a random number from 1 to 8
-
- // Use if statements to test the random number
- // and print out 1 of 8 random responses
-
-
- }
- }
- ====
- import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
- import java.util.ArrayList;
-
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("Magic8Ball");
- }
-
- @Test
- public void test1()
- {
- String output = getMethodOutput("main");
-
- boolean passed = output.length() > 0;
-
- passed = getResults("Output length > 0", "Output length of " + output.length(), "Prints a statement", passed);
- assertTrue(passed);
- }
+ public static void main(String[] args)
+ {
+ // Get a random number from 1 to 8
+ // Use if statements to test the random number
+ // and print out 1 of 8 random responses
- @Test
- public void test2()
- {
- String[] output = new String[200];
-
- for (int i = 0; i < output.length; i++) {
- output[i] = getMethodOutput("main");
- }
-
- ArrayList && 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
- :practice: T
- :answer_a: first case
- :answer_b: second case
- :answer_c: You will get a error because you can't divide by zero.
- :correct: c
- :feedback_a: 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");
-
-
+
|Groupwork| Programming Challenge : Truth Tables POGIL
------------------------------------------------------
.. |pogil| raw:: html
POGIL
-
+
.. |pogil role| raw:: html
POGIL role
-
+
.. |venn diagram| raw:: html
Venn diagram
-
-We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns.
+
+We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns.
Explore the following problems with your group:
-1. Draw or print a |Venn diagram| of 4 intersecting circles. Put the names of the 4 people in your group one in each circle. Write down the age of each person in your group in the circles. If two or more people are the same age, put the age in the intersecting parts of their circles. Write a Boolean expression that compares the age of each person in the group using ==, <, >, and &&, for example Ada's age > Alan's age && Alan's age == Grace's age. Then, ask each person in your group their favorite movie. If two or more people have the same favorite movie, put the movie in the intersecting parts of their circles. Write a Boolean expression that compares the favorite movies in the group using ==, !=, and &&, for example Ada's movie == Alan's movie && Alan's movie != Grace's movie. Think of 1 more comparison and write it in the circles and as a Boolean expression. Share the Boolean expressions with the class. (Thank you to Jill Westerlund of Hoover High School and Art Lopez of Sweetwater High School for this activity suggestion).
+1. Draw or print a |Venn diagram| of 4 intersecting circles. Put the names of the 4 people in your group one in each circle. Write down the age of each person in your group in the circles. If two or more people are the same age, put the age in the intersecting parts of their circles. Write a Boolean expression that compares the age of each person in the group using ``==``, ``<``, ``>``, and ``&&``, for example Ada's age ``>`` Alan's age ``&&`` Alan's age ``==`` Grace's age. Then, ask each person in your group their favorite movie. If two or more people have the same favorite movie, put the movie in the intersecting parts of their circles. Write a Boolean expression that compares the favorite movies in the group using ``==``, ``!=``, and ``&&``, for example Ada's movie ``==`` Alan's movie ``&&`` Alan's movie ``!=`` Grace's movie. Think of 1 more comparison and write it in the circles and as a Boolean expression. Share the Boolean expressions with the class. (Thank you to Jill Westerlund of Hoover High School and Art Lopez of Sweetwater High School for this activity suggestion).
-2. Write the sentence "If it's sunny, OR if the temperature is greater than 80 and it's not raining, I will go to the beach." as a Java if statement using an int variable ``temperature`` and boolean variables ``sunny`` and ``raining``. If the conditional is true, print out "Go to the beach!". So, you will go to beach on days that it is sunny in any temperature, or you will go to the beach on days when the temperature is over 80 degrees and it's not raining.
+2. Write the sentence "If it's sunny, OR if the temperature is greater than 80 and it's not raining, I will go to the beach." as a Java if statement using an int variable ``temperature`` and boolean variables ``sunny`` and ``raining``. If the conditional is true, print out "Go to the beach!". So, you will go to the beach on days that it is sunny in any temperature, or you will go to the beach on days when the temperature is over 80 degrees and it's not raining.
3. Complete a truth table for the if statement that you wrote in #2 with columns for sunny, temperature > 80, raining, and go to the beach.
@@ -485,81 +468,158 @@ Explore the following problems with your group:
:autograde: unittest
:practice: T
+ Challenge-3-5-truthtables: Test your boolean expression in an if statement below.
+ ~~~~
public class TruthTable
{
- public static void main(String[] args)
- {
- // Test multiple values for these variables
- boolean sunny = false;
- int temperature = 90;
- boolean raining = false;
-
- // Write an if statement for: If it's sunny,
- // OR if the temperature is greater than 80
- // and it's not raining, "Go to the beach!"
-
-
- }
+ public static void main(String[] args)
+ {
+ // Test multiple values for these variables
+ boolean sunny = false;
+ int temperature = 90;
+ boolean raining = false;
+
+ // Write an if statement for: If it's sunny,
+ // OR if the temperature is greater than 80
+ // and it's not raining, "Go to the beach!"
+
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
- public void testMain() throws IOException
- {
- String expect = "Go to the beach!";
- String output = getMethodOutput("main");
- String code = getCode();
- boolean passed;
- if (getCode().contains("boolean sunny = false"))
- passed = getResults(expect, output, "Prints Go to the beach! with initial input (sunny = false; temperature = 90; raining = false;)");
- else
- passed = getResults("sunny = false","sunny = true", "Set sunny to false to test");
-
- assertTrue(passed);
- }
-
- @Test
- public void testCodeContains1(){
- boolean ifStatement = checkCodeContains("conditional: if sunny", "if (sunny");
- assertTrue(ifStatement);
- }
+ public void testMain() throws IOException
+ {
+ String expect = "Go to the beach!";
+ String output = getMethodOutput("main");
+ String code = getCode();
+ boolean passed;
+ if (getCode().contains("boolean sunny = false"))
+ passed =
+ getResults(
+ expect,
+ output,
+ "Prints Go to the beach! with initial input (sunny = false; temperature"
+ + " = 90; raining = false;)");
+ else passed = getResults("sunny = false", "sunny = true", "Set sunny to false to test");
- @Test
- public void testCodeContains2(){
- boolean ifStatement1 = checkCodeContains("conditional: temperature greater than 80", "temperature > 80");
+ assertTrue(passed);
+ }
- assertTrue(ifStatement1);
- }
+ @Test
+ public void testCodeContains1()
+ {
+ boolean ifStatement = checkCodeContains("conditional: if", "if");
+ assertTrue(ifStatement);
+ }
- @Test
- public void testCodeContains4(){
- boolean ifStatement3 = checkCodeContains("and", "&&");
- assertTrue(ifStatement3);
- }
- @Test
- public void testCodeContains5(){
- boolean ifStatement3 = checkCodeContains("or", "||");
- assertTrue(ifStatement3);
- }
- }
+ @Test
+ public void testCodeContains2()
+ {
+ boolean ifStatement1 =
+ checkCodeContains("conditional: temperature greater than 80", "temperature > 80");
+
+ assertTrue(ifStatement1);
+ }
+
+ @Test
+ public void testCodeContains4()
+ {
+ boolean ifStatement3 = checkCodeContains("and", "&&");
+ assertTrue(ifStatement3);
+ }
+
+ @Test
+ public void testCodeContains5()
+ {
+ boolean ifStatement3 = checkCodeContains("or", "||");
+ assertTrue(ifStatement3);
+ }
+ }
-
Summary
--------
-- Logical operators !(not), &&(and), and ||(or) are used with Boolean values.
+- Logical operators ``!`` (not), ``&&`` (and), and ``||`` (or) are used with Boolean values.
+
+- ``A && B`` is ``true`` if both ``A`` and ``B`` are ``true``.
+
+- ``A || B`` is ``true`` if either ``A`` or ``B`` (or both) are ``true``.
+
+- ``!A`` is ``true`` if ``A`` is ``false``.
-- (A && B) is true if both A and B are true.
+- In Java, ``!`` has precedence (is executed before) ``&&`` which has precedence over ``||``. Parentheses can be used to force the order of execution in a different way.
-- (A || B) is true if either A or B (or both) are true.
+- When the result of a logical expression using ``&&`` or ``||`` can be determined by evaluating only the first Boolean operand, the second is not evaluated. This is known as **short-circuit evaluation**.
-- !(A) is true if A is false.
-- In Java, ! has precedence (is executed before) && which has precedence over ||. Parentheses can be used to force the order of execution in a different way.
+AP Practice
+------------
+
+.. mchoice:: AP3-5-1
+ :practice: T
+
+ Consider the following code segment. What is printed as a result of executing the code segment?
+
+ .. code-block:: java
+
+ int x = 10;
+ int y = 5;
+
+ if (x % 2 == 0 && y % 2 == 0 || x > y)
+ {
+ System.out.print("First ");
+
+ if (y * 2 == x || y > 5 && x <= 10)
+ {
+ System.out.print("Second ");
+ }
+ else
+ {
+ System.out.print("Third ");
+ }
+ }
+
+ - Nothing is printed out.
+
+ - Some of these conditions are true.
+
+ - First
+
+ - This is partially correct.
+
+ - Third
+
+ - Third cannot be printed out unless First is printed out first.
+
+ - First Second
+
+ + Good tracing!
+
+ - First Third
+
+ - Take another look at the second condition.
+
+
+Boolean Game
+---------------
+
+.. |game| raw:: html
+
+ game
+
+
+Try the game below written to practice Booleans. Click on **Booleans**, look at the color and number in the block and evaluate the boolean expression to choose true or false. Then, check on Compound for an added challenge. We encourage you to work in pairs and see how high a score you can get.
+
+.. raw:: html
-- When the result of a logical expression using && or || can be determined by evaluating only the first Boolean operand, the second is not evaluated. This is known as **short-circuit evaluation**.
\ No newline at end of file
+
+
diff --git a/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst b/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst
index 8329187ff..221504253 100644
--- a/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst
+++ b/_sources/Unit3-If-Statements/topic-3-6-DeMorgan.rst
@@ -1,83 +1,77 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 3-6-
- :start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+ :start: 1
+
.. raw:: html
-
+
+|Time90|
+
Equivalent Boolean Expressions (De Morgan's Laws)
=================================================
-.. index::
- single: De Morgan's Laws
- single: negation
+.. index::
+ single: De Morgan's Laws
+ single: negation
-What if you heard a rumor about a senior at your high school? And then you heard that the rumor wasn't true. Which part of "a senior at your high school" wasn't true? Maybe they weren't a senior? Or maybe they didn't go to your high school? You could write this as a logic statement like below using negation (!) and the AND (&&) operator since both parts have to be true for the whole statement to be true. (Thank you to Kevin Saxton from Kent School, CT for this example.)
+What if you heard a rumor about a senior at your high school? And then you heard that the rumor wasn't true - it wasn't a senior at your high school. Which part of "a senior at your high school" wasn't true? Maybe they weren't a senior? Or maybe they didn't go to your high school? You could write this as a logic statement like below using negation (``!``) and the **and** (``&&``) operator since both parts have to be true for the whole statement to be true. (Thank you to Kevin Saxton from Kent School, CT for this example.)
-.. code-block:: java
+.. code-block:: java
!(a && b)
-
+
a = "senior"
b = "at our high school"
-
+
+ // This means it is not true that (a) it is a senior
+ // and (b) someone at our high school.
In this lesson, you will learn about De Morgan's Laws which simplify statements like this. We know that !(a senior at our high school) could mean !(a senior) or !(at our high school). Let's learn more about De Morgan's Laws.
-De Morgan's Laws were developed by Augustus De Morgan in the 1800s. They show how to simplify the negation of a complex boolean expression, which is when there are multiple expressions joined by an AND (&&) or OR (||), such as ``(x < 3) && (y > 2)``. When you negate one of these complex expressions, you can simplify it by flipping the operators and end up with an equivalent expression. De Morgan's Laws state the following equivalencies. Here's an easy way to remember De Morgan's Laws: **move the NOT inside, AND becomes OR** and **move the NOT inside, OR becomes AND**.
+De Morgan's Laws
+----------------
+
+De Morgan's Laws were developed by Augustus De Morgan in the 1800s. They show how to simplify the negation of a complex boolean expression, which is when there are multiple expressions joined by an **and** (``&&``) or **or** (``||``), such as ``(x < 3) && (y > 2)``. When you negate one of these complex expressions, you can simplify it by flipping the operators and end up with an equivalent expression. De Morgan's Laws state the following equivalencies. Here's an easy way to remember De Morgan's Laws: **move the NOT inside, AND becomes OR** and **move the NOT inside, OR becomes AND**.
.. figure:: Figures/demorgan.png
:width: 400px
:align: center
:figclass: align-center
-
+
Figure 1: De Morgan's Laws to simplify complex expressions
In Java, De Morgan's Laws are written with the following operators:
- - **!(a && b)** is equivalent to **!a || !b**
-
- - **!(a || b)** is equivalent to **!a && !b**
-
+ - ``!(a && b)`` is equivalent to ``!a || !b``
+
+ - ``!(a || b)`` is equivalent to ``!a && !b``
+
Going back to our example above, !(a senior && at our high school) is equivalent to !(a senior) or !(at our high school) using De Morgan's Laws:
-.. code-block:: java
+.. code-block:: java
!(a && b) is equivalent to !a || !b
-
+
a = "senior"
b = "at our high school"
-
-You can also simplify negated boolean expressions that have relational operators like <, >, ==. You can remove negation by moving it inside and flipping the relational operator to its opposite sign. For example, not (c equals d) is the same as saying c does not equal d. An easy way to remember this is **Move the NOT inside, flip the sign** (== becomes !=, < becomes >=, and > becomes <=).
+You can also simplify negated boolean expressions that have relational operators like ``<``, ``>``, ``==``. You can move the negation inside the parentheses by flipping the relational operator to its opposite sign. For example, not (c equals d) is the same as saying c does not equal d. An easy way to remember this is **To move the NOT, flip the sign**. Notice that ``==`` becomes ``!=``, but ``<`` becomes ``>=``, ``>`` becomes ``<=``, ``<=`` becomes ``>``, and ``>=`` becomes ``<`` where the sign is flipped and an equal sign may also be added or removed.
+
+ - ``!(c == d)`` is equivalent to ``c != d``
+ - ``!(c != d)`` is equivalent to ``c == d``
+ - ``!(c < d)`` is equivalent to ``c >= d``
+ - ``!(c > d)`` is equivalent to ``c <= d``
+ - ``!(c <= d)`` is equivalent to ``c > d``
+ - ``!(c >= d)`` is equivalent to ``c < d``
- - !(c == d) is equivalent to (c != d)
- - !(c != d) is equivalent to (c == d)
- - !(c < d) is equivalent to (c >= d)
- - !(c > d) is equivalent to (c <= d)
- - !(c <= d) is equivalent to (c > d)
- - !(c >= d) is equivalent to (c < d)
+Truth Tables
+------------
-Although you do not have to memorize De Morgan's Laws for the CS A Exam, you should be able to show that two boolean expressions are equivalent. One way to do this is by using truth tables. For example, we can show that !(a && b) == !a || !b by constructing the truth table below and seeing that they give identical results for the 2 expressions (the last 2 columns in the table below are identical!).
+Although you do not have to memorize De Morgan's Laws for the CSA Exam, you should be able to show that two boolean expressions are equivalent. One way to do this is by using truth tables. For example, we can show that ``!(a && b)`` is equivalent to ``!a || !b`` by constructing the truth table below and seeing that they give identical results for the 2 expressions (the last 2 columns in the table below are identical!).
+-------+-------+-----------+----------+
| a | b | !(a && b) | !a || !b |
@@ -91,13 +85,16 @@ Although you do not have to memorize De Morgan's Laws for the CS A Exam, you sho
| false | false | true | true |
+-------+-------+-----------+----------+
-Often, you can simplify boolean expressions to create equivalent expressions. For example, applying De Morgan's Laws to ``!(x < 3 && y > 2)`` yields ``!(x < 3) || !(y > 2)`` as seen in the figure below. This can then be simplified further by moving the not operator inside and flipping the relation operators. So, ``!(x < 3) || !(y > 2)`` is simplified to ``(x >= 3 || y <= 2)`` where the relational operators are flipped and the negation is removed. These two simplification steps are seen below.
+Simplifying Boolean Expressions
+----------------------------------
+
+Often, you can simplify boolean expressions to create equivalent expressions. For example, applying De Morgan's Laws to ``!(x < 3 && y > 2)`` yields ``!(x < 3) || !(y > 2)`` as seen in the figure below. This can then be simplified further by flipping the relational operators to remove the not. So, ``!(x < 3) || !(y > 2)`` is simplified to ``(x >= 3 || y <= 2)`` where the relational operators are flipped and the negation is removed. These two simplification steps are seen below.
.. figure:: Figures/demorganex.png
:width: 400px
:align: center
:figclass: align-center
-
+
Figure 2: An example boolean expression simplified
@@ -115,46 +112,51 @@ Often, you can simplify boolean expressions to create equivalent expressions. Fo
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- int x = 2;
- int y = 3;
- System.out.println(!(x < 3 && y > 2));
- }
+ public static void main(String[] args)
+ {
+ int x = 2;
+ int y = 3;
+ System.out.println(!(x < 3 && y > 2));
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testChangedCode() {
- String origCode = "public class Test1 {public static void main(String[] args) { int x = 2; int y = 3; System.out.println(!(x < 3 && y > 2)); } }";
-
- boolean changed = codeChanged(origCode);
- assertTrue(changed);
- }
- }
-
-
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testChangedCode()
+ {
+ String origCode =
+ "public class Test1 {public static void main(String[] args) { int x = 2; int y = 3;"
+ + " System.out.println(!(x < 3 && y > 2)); } }";
+
+ boolean changed = codeChanged(origCode);
+ assertTrue(changed);
+ }
+ }
+
|Exercise| **Check your understanding**
.. mchoice:: qcbdm1_8
:practice: T
:answer_a: first case
- :answer_b: second case
+ :answer_b: second case
:correct: b
:feedback_a: This will be printed if x is greater or equal to 3 and y is less than or equal to 2. The first part is true but the second is false. Since the statements are joined by an and the complex expression is false.
:feedback_b: This will be printed if x is less than 3 or y is greater than 2. In this case the first will be false, but the second true so since the statements are joined with an or the complex expression is true.
- What is printed when the following code executes and x equals 4 and y equals 3?
-
- .. code-block:: java
+ What is printed when the following code executes and x equals 4 and y equals 3?
- int x = 4, y = 3;
- if (!(x < 3 || y > 2))
+ .. code-block:: java
+
+ int x = 4, y = 3;
+ if (!(x < 3 || y > 2))
{
System.out.println("first case");
}
@@ -162,21 +164,21 @@ Often, you can simplify boolean expressions to create equivalent expressions. Fo
{
System.out.println("second case");
}
-
+
.. mchoice:: qcbdm2_9
:practice: T
:answer_a: first case
- :answer_b: second 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.
+ :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
+ What is printed when the following code executes and x equals 4 and y equals 3?
- int x = 4, y = 3;
- if (!(x < 3 && y > 2))
+ .. code-block:: java
+
+ int x = 4, y = 3;
+ if (!(x < 3 && y > 2))
{
System.out.println("first case");
}
@@ -185,14 +187,14 @@ Often, you can simplify boolean expressions to create equivalent expressions. Fo
System.out.println("second case");
}
-
+
|Groupwork| Programming Challenge : Truth Tables POGIL
------------------------------------------------------
.. |pogil| raw:: html
POGIL
-
+
.. |pogil role| raw:: html
POGIL role
@@ -200,69 +202,76 @@ Often, you can simplify boolean expressions to create equivalent expressions. Fo
.. |this worksheet| raw:: html
this worksheet
-
-We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns.
-Explore the following problems with your group. You may use |this worksheet| to complete your truth tables. Assume that x is an integer value, for example -1, 0, or 1.
+We encourage you to do this activity as a |POGIL| (Process Oriented Guided Inquiry Learning) group activity. POGIL groups are self-managed teams of up to 4 students where everyone has a |pogil role| and works together to solve the problems, making sure that everyone in the team participates and learns.
-1. Complete a truth table for the boolean expression: !(x == 0 || x >= 1). Is this the set of positive or negative numbers? Is the expression true when x is positive? Or is it true when x is negative? You can try out the values when x is 1 or -1 or 0. Note that 0 is not positive or negative. You can try running the code below to check your answer.
+Explore the following problems with your group. You may use |this worksheet| to complete your truth tables. Assume that ``x`` is an integer value, for example -1, 0, or 1.
+1. Complete a truth table for the boolean expression: ``!(x == 0 || x >= 1)``. Is this the set of positive or negative numbers? Is the expression true when ``x`` is positive? Or is it true when ``x`` is negative? You can try out the values when ``x`` is 1 or -1 or 0. Note that 0 is not positive or negative. You can try running the code below to check your answer.
-2. Complete a truth table for the boolean expression: !(x == 0) && !(x >= 1). Is this the set of positive or negative numbers?
-3. Complete a truth table for the boolean expression: (x != 0) && (x < 1). Is this the set of positive or negative numbers?
+2. Complete a truth table for the boolean expression: ``!(x == 0) && !(x >= 1)``. Is this the set of positive or negative numbers?
+
+3. Complete a truth table for the boolean expression: ``(x != 0) && (x < 1)``. Is this the set of positive or negative numbers?
4. Are the 3 boolean expressions equivalent? Why or why not?
5. Test your answers using the active code window below.
-6. Complete the following exercises 3-6-3 through 3-6-7 in your POGIL groups.
+6. Complete the following multiple choice exercises in your POGIL groups. Show the application of DeMorgan's laws or the truth tables in each question on paper.
.. activecode:: challenge3-6-booleanExpr
:language: java
:autograde: unittest
-
- Are these 3 boolean expressions equivalent? 1. !(x == 0 || x >= 1) , 2. !(x == 0) && !(x >= 1) , 3. (x != 0) && (x < 1)
+
+ Are these 3 boolean expressions equivalent? 1. ``!(x == 0 || x >= 1)`` , 2. ``!(x == 0) && !(x >= 1)`` , 3. ``(x != 0) && (x < 1)``
~~~~
public class EquivalentExpressions
{
- public static void main(String[] args)
- {
- int x = -1; // try with x = -1, x = 0, and x = 1
- System.out.println(!(x == 0 || x >= 1));
- // add print statements for expressions in #2 and #3
- // to see if they are equivalent when x = -1, 0, and 1.
-
-
- }
+ public static void main(String[] args)
+ {
+ int x = -1; // try with x = -1, x = 0, and x = 1
+ System.out.println(!(x == 0 || x >= 1));
+ // add print statements for expressions in #2 and #3
+ // to see if they are equivalent when x = -1, 0, and 1.
+
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testChangedCode()
+ {
+ String origCode =
+ "public class EquivalentExpressions { public static void main(String[] args) { int"
+ + " x = -1; System.out.println(!(x == 0 || x >= 1)); } }";
+
+ boolean changed = codeChanged(origCode);
+ assertTrue(changed);
+ }
+
+ @Test
+ public void testAddedCode()
+ {
+ boolean output2 = checkCodeContains("(x != 0) && (x < 1)");
+ assertTrue(output2);
+ }
+
@Test
- public void testChangedCode() {
- String origCode = "public class EquivalentExpressions { public static void main(String[] args) { int x = -1; // try with x = -1, x = 0, and x = 1 \n System.out.println(!(x == 0 || x >= 1)); // add print statements for expressions in #2 and #3 // to see if they are equivalent when x = -1, 0, and 1. } }";
-
- boolean changed = codeChanged(origCode);
- assertTrue(changed);
- }
-
- @Test
- public void testAddedCode(){
- boolean output2 = checkCodeContains("(x != 0) && (x < 1)");
- assertTrue(output2);
- }
-
- @Test
- public void testAddedCode2(){
- boolean output3 = checkCodeContains("!(x == 0) && !(x >= 1)");
- assertTrue(output3);
- }
- }
+ public void testAddedCode2()
+ {
+ boolean output3 = checkCodeContains("!(x == 0) && !(x >= 1)");
+ assertTrue(output3);
+ }
+ }
.. mchoice:: qcbdm3_1
:practice: T
@@ -272,16 +281,16 @@ Explore the following problems with your group. You may use |this worksheet| to
: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_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
+ :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
+ Which of the following is the same as the code below?
+
+ .. code-block:: java
!(x > 2 && y < 4)
-
+
.. mchoice:: qcbdm4_2
:practice: T
:answer_a: (x != 2) || (y < 4)
@@ -294,17 +303,17 @@ Explore the following problems with your group. You may use |this worksheet| to
: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
+ Which of the following is the same as the code below?
+
+ .. code-block:: java
!(x == 2 && y > 4)
-
+
.. mchoice:: qcbdm5_3
:practice: T
:answer_a: (x == 5) || (y == 7)
:answer_b: (x == 5) && (y == 7)
- :answer_c: (x != 5) || (y != 7)
+ :answer_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 ==
@@ -312,12 +321,12 @@ Explore the following problems with your group. You may use |this worksheet| to
: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
+ Which of the following is the same as the code below?
+
+ .. code-block:: java
!(x!=5 && y!=7)
-
+
.. mchoice:: qcbdm6_4
:practice: T
:answer_a: (x > 5) && (y < 7)
@@ -331,14 +340,42 @@ Explore the following problems with your group. You may use |this worksheet| to
: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
+ Which of the following is the same as the code below?
+
+ .. code-block:: java
!(x<= 5 && y > 7)
-**AP CSA Sample Question**
+
+
+
+
+
+Summary
+--------
+
+- De Morgan’s Laws can be applied to Boolean expressions to create equivalent ones:
+
+ - ``!(a && b)`` is equivalent to ``!a || !b``
+ - ``!(a || b)`` is equivalent to ``!a && !b``
+
+- A negated expression with a relational operator can be simplified by flipping the relational operator to its opposite sign.
+
+ - ``!(c == d)`` is equivalent to ``c != d``
+ - ``!(c != d)`` is equivalent to ``c == d``
+ - ``!(c < d)`` is equivalent to ``c >= d``
+ - ``!(c > d)`` is equivalent to ``c <= d``
+ - ``!(c <= d)`` is equivalent to ``c > d``
+ - ``!(c >= d)`` is equivalent to ``c < d``
+
+- Truth tables can be used to prove that 2 Boolean expressions are identical.
+
+- Equivalent Boolean expressions will evaluate to the same value in all cases.
+
+
+AP Practice
+------------
.. mchoice:: apcsa-sample5
:practice: T
@@ -350,32 +387,8 @@ Explore the following problems with your group. You may use |this worksheet| to
:correct: b
:feedback_a: Try simplifying !(b ||a) or consider what happens if a and b are true.
:feedback_b: Yes, a && !(b || a) = a && !b && !a. Since (a && !a) can never be true, the result will always be false.
- :feedback_c: Try the expression with a = false. Is the result true?
+ :feedback_c: Try the expression with a = false. Is the result true?
:feedback_d: Try the expression with b = false with a = true and then try it with a = false. Is the result ever true?
:feedback_e: Try the expression with a = true. Is the result true?
Which of the following best describes the value of the Boolean expression: a && !(b || a)
-
-
-
-
-Summary
---------
-
-- De Morgan’s Laws can be applied to Boolean expressions to create equivalent ones:
-
- - !(a && b) is equivalent to !a || !b
- - !(a || b) is equivalent to !a && !b
-
-- A negated expression with a relational operator can be simplified by flipping the relational operator and removing the not.
-
- - !(c == d) is equivalent to (c != d)
- - !(c != d) is equivalent to (c == d)
- - !(c < d) is equivalent to (c >= d)
- - !(c > d) is equivalent to (c <= d)
- - !(c <= d) is equivalent to (c > d)
- - !(c >= d) is equivalent to (c < d)
-
-- Truth tables can be used to prove that 2 Boolean expressions are identical.
-
-- Equivalent Boolean expressions will evaluate to the same value in all cases.
\ No newline at end of file
diff --git a/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst b/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst
index d7435288f..dc8412b0e 100644
--- a/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst
+++ b/_sources/Unit3-If-Statements/topic-3-7-comparing-objects.rst
@@ -1,42 +1,29 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 3-7-
- :start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+ :start: 1
+
+|Time45|
+
Comparing Objects
=================
-Comparing objects is a little different than comparing primitive typed values like numbers. Objects can be very complex and have many attribute values or instance variables inside them. For example, the turtle objects have many instance variables like name, width, height, xPos, yPos, etc. When comparing two turtle objects, we need a specially written **equals** method to compare all of these values. In this lesson, we will take a look at String objects and how they are compared with == vs. the equals method.
+Comparing objects is a little different than comparing primitive typed values like numbers. Objects can be very complex and have many attribute values or instance variables inside them. For example, the ``Turtle`` objects have many instance variables like ``name``, ``width``, ``height``, ``xPos``, ``yPos``, etc. When comparing two ``Turtle`` objects, we need a specially written **equals** method to compare all of these values. In this lesson, we will take a look at ``String`` objects and the difference between comparing them with ``==`` vs. the ``equals`` method.
String Equality
---------------
-.. index::
- pair: String; equality
- pair: String; equals
+.. index::
+ pair: String; equality
+ pair: String; equals
+
+The **equals** method for Strings compares two strings letter by letter. ``s1.equals(s2)`` is true if ``s1`` and ``s2`` have all the same characters in the same order. With ``Strings`` and other objects, you almost always use ``equals`` instead of ``==`` to check their equality.
-The **equals** method for Strings compares two strings letter by letter. ``s1.equals(s2)`` is true if s1 and s2 have all the same characters in the same order. With Strings and other objects, you almost always use equals instead of == to check their equality.
-
-When the operator ``==`` is used to compare object variables, it returns true when the two variables *refer to the same object*. These variables are called **object references** and **aliases** for the same object. With strings this happens when one string variable is set to another.
+When the operator ``==`` is used to compare object variables, it returns true when the two variables *refer to the same object*. These variables are called **object references** and **aliases** for the same object. With strings this happens when one string variable is set to another.
.. figure:: Figures/stringEquality.png
@@ -46,157 +33,132 @@ When the operator ``==`` is used to compare object variables, it returns true wh
Figure 1: String aliases
-|CodingEx| **Coding Exercise**
+|CodingEx| **Coding Exercise**
.. activecode:: lcse1
:language: java
- :autograde: unittest
-
+ :autograde: unittest
+
If you run the following, what will be printed?
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- String s1 = new String("Hello");
- String s2 = new String("Bye");
- String s3 = s2;
- System.out.println(s3);
- System.out.println(s2 == s3);
- System.out.println(s2.equals(s3));
- }
+ public static void main(String[] args)
+ {
+ String s1 = new String("Hello");
+ String s2 = new String("Bye");
+ String s3 = s2; // s3 is now an alias for s2
+ System.out.println(s3);
+ System.out.println(s2 == s3);
+ System.out.println(s2.equals(s3));
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Bye\ntrue\ntrue\n";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
-The code above will print ``Bye`` since s3 has been assigned to a copy of the value in s2 which is an object reference to the String object that has the characters "Bye" in it.
-In addition, ``s2 == s3`` will be true since the two variables refer to the same object. Also, ``s2.equals(s3)`` will also be true; again since the two variables refer to the same object, of course the characters will be the same.
+ import java.io.*;
-.. figure:: Figures/stringRefExamplev2.png
- :width: 250px
- :align: center
- :figclass: align-center
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Bye\ntrue\ntrue\n";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
- Figure 2: Several String variables with references to objects of the String class.
+The following `video
+.. |JuiceMind| raw:: html
-|CodingEx| **Coding Exercise**
+ JuiceMind
-.. |numbers on repl.it| raw:: html
+.. |replit| raw:: html
- numbers on repl.it
+ replit
-Here's another example with |numbers on repl.it|. This code calculates the average of positive numbers, but it is missing the condition for the loop on line 14. Let's use -1 as the **sentinel value**. Add the condition to the while loop to run while the user does not input -1. What would happen if you forgot step 3 (change the loop variable - get a new input)? Try commenting out line 19 with // to see what happens (note there is a stop button at the top!).
+Here's another example of an input-controlled loop, which you can try online with |JuiceMind| or |replit|. This code calculates the average of positive numbers. The number -1 is used as the **sentinel value**. The while loop will run while the user does not input -1. What would happen if you forgot step 3 (change the loop variable - get a new input)? Remember that skipping step 3 will often lead to an infinite loop!
-.. raw:: html
+.. code-block:: java
-
+ // 1. initialize the loop variable (get the first number)
+ System.out.print("Please enter a number to average in or -1 to stop: ");
+ number = scan.nextInt();
+ // 2. test the loop variable (against sentinel value)
+ while (number != -1)
+ {
+ sum += number; // add number to sum
+ count++; // count the number
+ // 3. Change the loop variable (get a new number)
+ System.out.print("Please enter a number to average in or -1 to stop: ");
+ number = scan.nextInt();
+ }
+ System.out.println(count);
+ // calculate average
+ average = (double) sum/count;
+ System.out.println("The average is " + average);
There are standard algorithms that use loops to compute the sum or average like above, or determine the minimum or maximum value entered, or the frequency of a certain condition. You can also use loops to identify if some integers are evenly divisible by other integers or identify the individual digits in an integer. We will see a lot more of these algorithms in Unit 6 with loops and arrays.
@@ -364,7 +448,7 @@ There are standard algorithms that use loops to compute the sum or average like
.. image:: Figures/questionmark.jpg
:width: 100
:align: left
-
+
We encourage you to work in pairs on this guessing game. In the guessing game, the computer picks a random number from 0-100 and you have to guess it. After each guess, the computer will give you clues like "Too high" or "Too low". Here's the pseudocode for the guessing game. **Pseudocode** is an English description or plan of what your code will do step by step. What's the loop variable for this program? Can you identify the 3 steps of writing this loop with respect to the loop variable?
1. Choose a random number from 0-100
@@ -374,7 +458,7 @@ We encourage you to work in pairs on this guessing game. In the guessing game, t
- If the guess is less than the random number, print out "Too low!"
- If the guess is greater than the random number, print out "Too high!"
- Get a new guess (save it into the same variable)
-
+
4. Print out something like "You got it!"
As an extension to this project, you can add a counter variable to count how many guesses the user took and print it out when they guess correctly.
@@ -384,126 +468,165 @@ When you finish and run your program, what is a good guessing strategy for guess
.. |Scanner class| raw:: html
Scanner class
-
-.. |repl.it| raw:: html
- repl.it
-
-For this project, you will need to use the |Scanner class| for input and |repl.it| or another IDE of your choice.
+.. |JuiceMindGuess| raw:: html
+
+ JuiceMind
-.. raw:: html
+.. |replitGuess| raw:: html
-
+ replit
+For this project, you can use the |Scanner class| for input and |JuiceMindGuess| or |replitGuess| or another IDE of your choice.
.. activecode:: challenge4-1-loop-GuessingGame-autograde
:language: java
- :autograde: unittest
+ :autograde: unittest
- Copy and paste all of your code from your repl.it and run to see if it passes the autograder tests. Include the link to your repl.it code in comments. Note that this code will only run with the autograder's input and will not ask the user for input.
+ Complete the code for the guessing game below. If you did this code in |JuiceMindGuess| or |replitGuess| or your own IDE, you can paste in your code to see if it passes the autograder tests. Note that this code will only run with the autograder's input and will not ask the user for input.
~~~~
- // Copy in your link to your code on repl.it here:
- // Copy in all of your code from repl.it below (include import and public class Main)
-
-
- ====
- import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
+ import java.util.Scanner;
- public class RunestoneTests extends CodeTestHelper
+ public class Main
+ {
+ public static void main(String[] args)
{
- public RunestoneTests() {
- super("Main", input1.replaceAll(" ", "\n")); // For Book
- //super("GuessingGame", input1.replaceAll(" ", "\n")); // For Repl.it
- }
+ Scanner scan = new Scanner(System.in);
+ // Choose a random number from 0-100
+
- private static int goal = 1;
- private static String input1 = "100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0";
- private static String input2 = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
- private String output1, output2;
+ // Ask the user to guess a number from 0 to 100
+ // Get the first guess using scan.nextInt();
+
+ // Loop while the guess does not equal the random number,
- @Test
- public void test1()
- {
- String input = input1.replaceAll(" ", "\n");
- String output = getMethodOutputWithInput("main", input);
- output1 = output;
+ // If the guess is less than the random number, print out "Too low!"
+
+ // If the guess is greater than the random number, print out "Too high!"
+
+ // Get a new guess (save it into the same variable)
+
- String[] lines = output.split("\n");
+ // Print out something like "You got it!"
- boolean passed = lines.length >= goal;
- passed = getResults(">" + goal +" lines", "" + lines.length + " lines", "Outputs at least " + goal +" lines", passed);
- assertTrue(passed);
- }
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
- @Test
- public void test2()
- {
- String input = input2.replaceAll(" ", "\n");
- String output = getMethodOutputWithInput("main", input);
- output2 = output;
+ import org.junit.*;
- if (output1 == null) {
- input = input1.replaceAll(" ", "\n");
- output1 = getMethodOutputWithInput("main", input);
- }
+ import java.io.*;
- boolean passed = !output1.equals(output2);
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Main", input1.replaceAll(" ", "\n")); // For Book
+ // super("GuessingGame", input1.replaceAll(" ", "\n")); // For replit.com
+ }
- passed = getResults("true", "" + passed, "Outputs different results for different inputs", passed);
- assertTrue(passed);
- }
+ private static int goal = 1;
+ private static String input1 =
+ "100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73"
+ + " 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47"
+ + " 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21"
+ + " 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0";
+ private static String input2 =
+ "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31"
+ + " 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57"
+ + " 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83"
+ + " 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
+ private String output1, output2;
+
+ @Test
+ public void test1()
+ {
+ String input = input1.replaceAll(" ", "\n");
+ String output = getMethodOutputWithInput("main", input);
+ output1 = output;
- @Test
- public void test3()
- {
- String code = getCode();
- int num = countOccurences(code, "if");
- boolean passed = num >= 2;
+ String[] lines = output.split("\n");
- getResults("2", "" + num, "Number of if statements", passed);
- assertTrue(passed);
- }
+ boolean passed = lines.length >= goal;
- @Test
- public void test4()
- {
- boolean passed = checkCodeContainsRegex("while loop", "while(*)");
- assertTrue(passed);
- }
+ passed =
+ getResults(
+ ">" + goal + " lines",
+ "" + lines.length + " lines",
+ "Outputs at least " + goal + " lines",
+ passed);
+ assertTrue(passed);
+ }
- @Test
- public void test5()
- {
- String input = input1.replaceAll(" ", "\n");
- int[] values = new int[10];
+ @Test
+ public void test2()
+ {
+ String input = input2.replaceAll(" ", "\n");
+ String output = getMethodOutputWithInput("main", input);
+ output2 = output;
- for (int i = 0; i < values.length; i++) {
- String output = getMethodOutputWithInput("main", input);
- values[i] = output.split("\n").length;
- }
+ if (output1 == null)
+ {
+ input = input1.replaceAll(" ", "\n");
+ output1 = getMethodOutputWithInput("main", input);
+ }
- boolean passed = false;
- for (int i = 0; i < values.length-1; i++) {
- if (values[i] != values[i+1])
- passed = true;
+ boolean passed = !output1.equals(output2);
- }
+ passed =
+ getResults(
+ "true",
+ "" + passed,
+ "Outputs different results for different inputs",
+ passed);
+ assertTrue(passed);
+ }
- passed = getResults("true", "" + passed, "Guesses random numbers", passed);
- assertTrue(passed);
- }
- }
+ @Test
+ public void test3()
+ {
+ String code = getCode();
+ int num = countOccurences(code, "if");
+ boolean passed = num >= 1;
+
+ getResults(">=1", "" + num, "Number of if statements", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test4()
+ {
+ // boolean passed = checkCodeContainsRegex("while loop", "while(*)");
+ boolean passed = checkCodeContains("while loop", "while");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test5()
+ {
+ String input = input1.replaceAll(" ", "\n");
+ int[] values = new int[10];
+
+ for (int i = 0; i < values.length; i++)
+ {
+ String output = getMethodOutputWithInput("main", input);
+ values[i] = output.split("\n").length;
+ }
-
-.. shortanswer:: challenge4-1-loop-GuessingGame
+ boolean passed = false;
+ for (int i = 0; i < values.length - 1; i++)
+ {
+ if (values[i] != values[i + 1]) passed = true;
+ }
+
+ passed = getResults("true", "" + passed, "Guesses random numbers", passed);
+ assertTrue(passed);
+ }
+ }
- (Old short answer - obsolete) After you complete your code on repl, paste in a link to it (click on share) here.
-
-
Summary
-------------------
@@ -515,89 +638,108 @@ Summary
- Initialize the loop variable
- Test the loop variable
- Change the loop variable
-
-- In loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the expression evaluates to false which signals to exit the loop. If the Boolean expression evaluates to false initially, the loop body is not executed at all.
-- A loop is an **infinite loop** when the Boolean expression always evaluates to true so that the loop never ends.
+- In ``while`` loops, the Boolean expression is evaluated before each iteration
+ of the loop body, including the first. When the expression evaluates to true,
+ the loop body is executed. This continues until the expression evaluates to
+ false which signals to exit the loop.
+
+- If the Boolean expression evaluates to false initially, the loop body is not
+ executed at all.
-- **Off by one** errors occur when the iteration statement loops one time too many or one time too few.
+- A loop is an **infinite loop** when the Boolean expression always evaluates to
+ true so that the loop never ends.
-- If the Boolean expression evaluates to false initially, the loop body is not executed at all.
+- **Off-by-one** errors occur when the iteration statement loops one time too
+ many or one time too few.
-- **Input-controlled loops** often use a **sentinel value** that is input by the user like "bye" or -1 as the condition for the loop to stop. Input-controlled loops are not on the AP CS A exam, but are very useful to accept data from the user.
+- **Input-controlled loops** often use a **sentinel value** that is input by the
+ user like "bye" or -1 as the condition for the loop to stop. Input-controlled
+ loops are not on the AP CSA exam, but are very useful to accept data from the
+ user.
- There are standard algorithms to compute a sum or average.
-.. Here is an example ``while`` loop that just prints the numbers until 0 is reached. Can you modify it to print 0 too?
-
-.. .. activecode:: while_loop_ex1
- :language: java
-
- public class Test
- {
- public static void main(String[] args)
- {
- int x = 3;
- while (x > 0)
- {
- System.out.println(x);
- x = x - 1;
- }
- }
- }
-
-.. Here is an example ``for`` loop that just prints the numbers until 0 is reached. Can you modify it to print 0 too?
-
-.. .. activecode:: for_loop_ex1
- :language: java
-
- public class Test
- {
- public static void main(String[] args)
- {
- for (int x = 3; x > 0; x--)
- {
- System.out.println(x);
- }
- }
- }
-
-.. Which of the two loops above takes less code? While you can write any loop with either a ``while`` or ``for``, programmers tend to use the ``while`` when they don't know how many times the loop will execute and the ``for`` when they know the number of times to execute the loop. The problem with using a ``while`` loop to execute a loop a certain number of times is that you have to remember to update the variable in the loop. The ``for`` loop allows you to specify all of the important things about a loop in one place (what value do variables start at, what is the condition to test, and how the loop variables change).
-.. **Check your understanding**
+AP Practice
+------------
-.. .. clickablearea:: click_while1
- :question: Click on all the statements that are part of the body of the while loop. If you make a mistake you can click on the statement again to unhighlight it.
- :iscode:
- :feedback: Remember, the body of a loop is all the statements between the { and } after the while keyword or single statement following the while if there are no {}.
-
- :click-incorrect:int x = 5;:endclick:
- :click-incorrect:while (x > 0):endclick:
- :click-incorrect:{:endclick:
- :click-correct:System.out.println(x);:endclick:
- :click-correct:x = x - 1;:endclick:
- :click-incorrect:}:endclick:
-
-.. .. clickablearea:: click_for1
- :question: Click on all the statements that are part of the body of the for loop. If you make a mistake you can click on the statement again to unhighlight it.
- :iscode:
- :feedback: Remember, the body of a loop is all the statements between the { and } after the for declaration or a single statement following the for declaration if there are no {}.
-
- :click-incorrect:for (int x = 5; x > 0; x--):endclick:
- :click-correct:System.out.println(x);:endclick:
-
-.. .. clickablearea:: click_for2
- :question: Click on all the statements that are part of the body of the for loop. If you make a mistake you can click on the statement again to unhighlight it.
- :iscode:
- :feedback: Remember, the body of a loop is all the statements between the { and } after the for declaration or single statement following the for declaration if there are no {}. Java doesn't require the body to be indented, but you should indent it to make it easier to see that the statements are part of the loop.
-
- :click-incorrect:String message1 = "I ";:endclick:
- :click-incorrect:String message2a = "love ";:endclick:
- :click-incorrect:String message3 = "you";:endclick:
- :click-incorrect:String message2b = "miss ";:endclick:
- :click-incorrect:for (int x = 1; x < 4; x++):endclick:
- :click-incorrect:{:endclick:
- :click-correct:System.out.println(message1 + message2a + message3);:endclick:
- :click-correct:System.out.println(message1 + message2b + message3);:endclick:
- :click-incorrect:}:endclick:
-
+.. mchoice:: AP4-1-1
+ :practice: T
+
+ Consider the following code segment.
+
+ .. code-block:: java
+
+ int n = 35;
+ int result = 1;
+ while (n > 0)
+ {
+ int d = n % 10;
+ result *= d;
+ n /= 10;
+ }
+ System.out.println(result);
+
+ What is the output after the code has been executed?
+
+ - 35
+
+ - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1.
+
+ - 15
+
+ + Correct! The digits in n = 35 are 3 and 5 and 3*5 = 15.
+
+ - 10
+
+ - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1.
+
+ - 8
+
+ - Although the sum of the digits in 35 are 8. This code uses multiplication.
+
+ - 33
+
+ - Keep track of the variables n, d, and result. Watch the tracing video in lesson 4.1.
+
+.. mchoice:: AP4-1-2
+ :practice: T
+
+ Consider the following code segment which is intended to print out the even numbers from 0 to 8 (including 8).
+
+ .. code-block:: java
+
+ int count = 0;
+ /* missing loop header */
+ {
+ if (count % 2 == 0)
+ {
+ System.out.println(count);
+ }
+ count++;
+ }
+
+ Which of the following could replace the missing loop header to ensure that the code segment
+ will work as intended to print out the even numbers from 0 to 8?
+
+
+ - while (count > 0)
+
+ - This would cause an infinite loop.
+
+ - while (count >= 8)
+
+ - This would not print out anything since count is 0 before the loop and not greater than 8.
+
+ - while (count < 8)
+
+ - This would print out one too few numbers and would stop before it printed out 8.
+
+ - while (count < 10)
+
+ + Correct! This would stop the loop when count is 10.
+
+ - while (count <= 10)
+
+ - This would print out one too many numbers, 0, 2, 4, 6, 8, 10.
diff --git a/_sources/Unit4-Iteration/topic-4-2-for-loops.rst b/_sources/Unit4-Iteration/topic-4-2-for-loops.rst
index 935b41ac6..30ebc5bd1 100644
--- a/_sources/Unit4-Iteration/topic-4-2-for-loops.rst
+++ b/_sources/Unit4-Iteration/topic-4-2-for-loops.rst
@@ -1,34 +1,21 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 4-2-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
.. |github| raw:: html
here
-
+
+|Time90|
+
For Loops
=========
-.. index::
- single: for loop
- pair: loop; for
+.. index::
+ single: for loop
+ pair: loop; for
Another type of loop in Java is a **for loop**. This is usually used when you know how many times you want the loop to execute. It is often a simple **counter-controlled loop** to do the loop body a set number of times.
@@ -40,13 +27,15 @@ If you took AP CSP with a block programming language like App Inventor, you prob
:width: 100%
:align: center
:figclass: align-center
-
+
Figure 1: Comparing App Inventor and Java for loops
+
+
Three Parts of a For Loop
--------------------------
-A for-loop combines all 3 parts of writing a loop in one line to initialize, test, and change the loop control variable. The 3 parts are separated by semicolons (``;``). Each of the three parts of a ``for`` loop declaration is optional (initialization, condition, and change), but the semicolons are not optional.
+A for-loop combines all 3 parts of writing a loop in one line to initialize, test, and change the loop control variable. The 3 parts are separated by semicolons (``;``). Each of the three parts of a ``for`` loop declaration is optional (initialization, condition, and change), but the semicolons are not optional.
.. code-block:: java
@@ -54,26 +43,33 @@ A for-loop combines all 3 parts of writing a loop in one line to initialize, tes
{
loop body
}
-
-The for-loop is almost a shortcut way to write a while loop with all three steps that you need in one line. One of the strange things about a ``for`` loop is that the code doesn't actually execute where you see it in the declaration. The code in the initialization area is executed only one time before the loop begins, the test condition is checked each time through the loop and the loop continues as long as the condition is true, and the loop control variable change is done at the end of each execution of the body of the loop, just like a while loop. When the loop condition is false, execution will continue at the next statement after the body of the loop.
-.. figure:: Figures/ForLoopFlow.png
- :width: 250px
+The for-loop is almost a shortcut way to write a while loop with all three steps that you need in one line.
+
+.. figure:: Figures/compareForAndWhile.png
+ :width: 600px
:align: center
:figclass: align-center
- Figure 2: Control flow in a for loop
-
-
-You can compare a ``while`` loop to a ``for`` loop to understand that a ``for`` loop actually executes like a ``while`` loop does if you use the ``while`` loop to repeat the body of the loop a specific number of times.
+ Figure 2: Showing how a for loop maps to a while loop
-.. figure:: Figures/compareForAndWhile.png
- :width: 600px
+Watch the following `video (int i = 3; i < 8; ) but it does increment i in the change part (int i = 3; i < 8; i++).
- :feedback_d: The value of i is set to 3 before the loop executes and the loop stops when i is equal to 8. So the last time through the loop i is equal to 7.
+ :feedback_d: The value of i is set to 3 before the loop executes and the loop stops when i is equal to 8. So the last time through the loop i is equal to 7.
What does the following code print?
-
- .. code-block:: java
- for (int i = 3; i < 8; i++)
- {
+ .. code-block:: java
+
+ for (int i = 3; i < 8; i++)
+ {
System.out.print(i + " ");
}
-
+
.. mchoice:: qlb_3_2
:practice: T
:answer_a: 3 4 5 6 7 8
- :answer_b: 0 1 2 3 4 5 6 7 8 9
+ :answer_b: 0 1 2 3 4 5 6 7 8 9
:answer_c: 1 2 3 4 5 6 7 8 9 10
:answer_d: 1 3 5 7 9
:correct: c
- :feedback_a: What is i set to in the initialization area?
- :feedback_b: What is i set to in the initialization area?
- :feedback_c: The value of i starts at 1 and this loop will execute until i equals 11. The last time through the loop the value of i is 10.
- :feedback_d: This loop changes i by 1 each time in the change area.
+ :feedback_a: What is i set to in the initialization area?
+ :feedback_b: What is i set to in the initialization area?
+ :feedback_c: The value of i starts at 1 and this loop will execute until i equals 11. The last time through the loop the value of i is 10.
+ :feedback_d: This loop changes i by 1 each time in the change area.
What does the following code print?
-
- .. code-block:: java
- for (int i = 1; i <= 10; i++)
- {
+ .. code-block:: java
+
+ for (int i = 1; i <= 10; i++)
+ {
System.out.print(i + " ");
}
-
+
.. mchoice:: qlb_3_3
:practice: T
:answer_a: 10
@@ -251,19 +243,19 @@ You can compare a ``while`` loop to a ``for`` loop to understand that a ``for``
:correct: c
:feedback_a: This would be true if i started at 0 and ended at 9. Does it?
:feedback_b: Since i starts at 3 and the last time through the loop it is 9 the loop executes 7 times (9 - 3 + 1 = 7)
- :feedback_c: How many numbers are between 3 and 9 (including 3 and 9)?
- :feedback_d: This would be true if i started at 0 and the value of i the last time through the loop it was 8.
+ :feedback_c: How many numbers are between 3 and 9 (including 3 and 9)?
+ :feedback_d: This would be true if i started at 0 and the value of i the last time through the loop it was 8.
+
+ How many times does the following method print a ``*``?
- How many times does the following method print a ``*``?
-
- .. code-block:: java
+ .. code-block:: java
- for (int i = 3; i <= 9; i++)
- {
- System.out.print("*");
+ for (int i = 3; i <= 9; i++)
+ {
+ System.out.print("*");
}
-
-
+
+
.. parsonsprob:: print_evens
:numbered: left
@@ -275,9 +267,7 @@ You can compare a ``while`` loop to a ``for`` loop to understand that a ``for``
public static void printEvens()
{
=====
- for (int i = 0;
- i <= 10;
- i+=2)
+ for (int i = 0; i <= 10; i+=2)
{
=====
System.out.println(i);
@@ -285,92 +275,93 @@ You can compare a ``while`` loop to a ``for`` loop to understand that a ``for``
} // end for
=====
} // end method
-
Decrementing Loops
-------------------
-
-You can also count backwards in a loop starting from the last number and decrementing down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop. For example, "for (int i=5; i > 0; i--)`` counts from 5 down to 1.
+
+You can also count backwards in a loop starting from the last number and decrementing down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop. For example, ``for (int i=5; i > 0; i--)`` counts from 5 down to 1.
|CodingEx| **Coding Exercise**
.. activecode:: lcfcp1
:language: java
:autograde: unittest
-
+
What do you think will happen when you run the code below? How would it change if you changed line 11 to initialize i's value to 3? Try the Code Lens button to visualize and trace through this code.
~~~~
public class SongTest
{
- public static void printPopSong()
- {
- String line1 = " bottles of pop on the wall";
- String line2 = " bottles of pop";
- String line3 = "Take one down and pass it around";
-
- // loop 5 times (5, 4, 3, 2, 1)
- for (int i = 5; i > 0; i--)
- {
- System.out.println(i + line1);
- System.out.println(i + line2);
- System.out.println(line3);
- System.out.println((i - 1) + line1);
- System.out.println();
- }
- }
-
- public static void main(String[] args)
- {
- SongTest.printPopSong();
- }
+ public static void printPopSong()
+ {
+ String line1 = " bottles of pop on the wall";
+ String line2 = " bottles of pop";
+ String line3 = "Take one down and pass it around";
+
+ // loop 5 times (5, 4, 3, 2, 1)
+ for (int i = 5; i > 0; i--)
+ {
+ System.out.println(i + line1);
+ System.out.println(i + line2);
+ System.out.println(line3);
+ System.out.println((i - 1) + line1);
+ System.out.println();
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ SongTest.printPopSong();
+ }
}
+
====
// Test Code for Lesson 4.1 - popSong
- import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import java.io.*;
+ import static org.junit.Assert.*;
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("SongTest");
- }
+ import org.junit.Test;
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "3 bottles of pop on the wall";
+ import java.io.*;
- String expect1 = expect.split("\n")[0];
- String output1 = output.split("\n")[0];
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("SongTest");
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "3 bottles of pop on the wall";
+
+ String expect1 = expect.split("\n")[0];
+ String output1 = output.split("\n")[0];
+
+ boolean passed = output.contains(expect);
+ passed = getResults(expect1, output1, "Print the song from 3", passed);
+ assertTrue(passed);
+ }
- boolean passed = output.contains(expect);
- passed = getResults(expect1, output1, "Print the song from 3", passed);
- assertTrue(passed);
- }
+ @Test
+ public void testMain2() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "5 bottles of pop on the wall";
- @Test
- public void testMain2() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "5 bottles of pop on the wall";
+ boolean passed = !output.contains(expect);
- boolean passed = !output.contains(expect);
+ String expect1 = expect.split("\n")[0];
+ String output1 = output.split("\n")[0];
- String expect1 = expect.split("\n")[0];
- String output1 = output.split("\n")[0];
+ passed = getResults(expect1, output1, "Do not start loop from 5", passed);
+ assertTrue(passed);
+ }
+ }
- passed = getResults(expect1, output1, "Do not start loop from 5", passed);
- assertTrue(passed);
- }
- }
-
-The method **printPopSong** prints the words to a song. It initializes the value of the variable i equal to 5 and then checks if i is greater than 0. Since 5 is greater than 0, the body of the loop executes. Before the condition is checked again, i is decreased by 1. When the value in i is equal to 0 the loop stops executing.
+The method **printPopSong** prints the words to a song. It initializes the value of the variable i equal to 5 and then checks if i is greater than 0. Since 5 is greater than 0, the body of the loop executes. Before the condition is checked again, i is decreased by 1. When the value in i is equal to 0 the loop stops executing.
@@ -378,49 +369,46 @@ The method **printPopSong** prints the words to a song. It initializes the valu
:language: java
:autograde: unittest
:practice: T
-
- Can you make the loop count by 2s backwards? It should print out 5 3 1? Remember to change all 3 parts of the for loop.
+
+ Can you make the loop count by 2s backwards? It should print out 5 3 1? Remember to change all 3 parts of the for loop.
~~~~
public class ForLoop
{
- public static void main(String[] args)
- {
- for(int count = 1; count <= 5; count++)
- {
- System.out.println(count);
- }
- }
+ public static void main(String[] args)
+ {
+ for (int count = 1; count <= 5; count++)
+ {
+ System.out.println(count);
+ }
+ }
}
-
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "5\n3\n1";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "5\n3\n1";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
}
-
-
-
Turtle Loops
------------
-
-|CodingEx| **Coding Exercise**
-Do you remember when we used the turtle objects to draw shapes? To create a square without loops we had to repeat code to go forward and turn 90 degrees to the right 4 times like below. Can you change the code below to remove the repeated lines of code and use a loop to draw 4 sides of the square? Did you notice that the code becomes a lot shorter? You should only need 1 forward and 1 turn command in the loop. Whenever you find yourself repeating code, try to use a loop instead!
+|CodingEx| **Coding Exercise**
-(If the code below does not work for you, you can copy the code into this |repl link| (refresh page after forking and if it gets stuck) or download the files |github| to use in your own IDE.)
+Do you remember when we used the turtle objects to draw shapes? To create a square without loops we had to repeat code to go forward and turn 90 degrees to the right 4 times like below. Can you change the code below to remove the repeated lines of code and use a loop to draw 4 sides of the square? Did you notice that the code becomes a lot shorter? You should only need 1 call to forward and 1 call to turn in the loop. Whenever you find yourself repeating code, try to use a loop instead!
.. activecode:: TurtleSquare
:language: java
@@ -429,47 +417,50 @@ Do you remember when we used the turtle objects to draw shapes? To create a squa
Can you change the code below to remove the repeated lines of code and use a loop to draw 4 sides of the square?
~~~~
- import java.util.*;
import java.awt.*;
+ import java.util.*;
public class TurtleDrawSquare
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- Turtle yertle = new Turtle(world);
-
- // Change the following code to use a for loop to draw the square
- yertle.forward();
- yertle.turn(90);
- yertle.forward();
- yertle.turn(90);
- yertle.forward();
- yertle.turn(90);
- yertle.forward();
- yertle.turn(90);
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ Turtle yertle = new Turtle(world);
+
+ // Change the following code to use a for loop to draw the square
+ yertle.forward();
+ yertle.turn(90);
+ yertle.forward();
+ yertle.turn(90);
+ yertle.forward();
+ yertle.turn(90);
+ yertle.forward();
+ yertle.turn(90);
+
+ world.show(true);
+ }
}
-
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleDrawSquare");
}
@Test
public void test1()
{
- String target = "for (int * = #; * ? #; *~)";
- boolean passed = checkCodeContains("for loop", target);
- assertTrue(passed);
+ String target = "for (int * = #; * ? #; *~)";
+ boolean passed = checkCodeContainsRegex("for loop", target);
+ assertTrue(passed);
}
@Test
@@ -482,7 +473,12 @@ Do you remember when we used the turtle objects to draw shapes? To create a squa
boolean passed = count == 1;
- passed = getResults("1 forward()", "" + count + " forward()", "Should only need forward() once", passed);
+ passed =
+ getResults(
+ "1 forward()",
+ "" + count + " forward()",
+ "Should only need forward() once",
+ passed);
assertTrue(passed);
}
@@ -496,7 +492,12 @@ Do you remember when we used the turtle objects to draw shapes? To create a squa
boolean passed = count == 1;
- passed = getResults("1 turn(90)", "" + count + " turn(90)", "Should only need turn(90) once", passed);
+ passed =
+ getResults(
+ "1 turn(90)",
+ "" + count + " turn(90)",
+ "Should only need turn(90) once",
+ passed);
assertTrue(passed);
}
}
@@ -504,63 +505,71 @@ Do you remember when we used the turtle objects to draw shapes? To create a squa
|Groupwork| Programming Challenge : Turtles Drawing Shapes
----------------------------------------------------------
-.. |repl link| raw:: html
+.. |replit| raw:: html
+
+ replit
+
+.. |JuiceMind| raw:: html
- repl.it link
+ JuiceMind
-In the last exercise, you used a for-loop to have the turtle draw a square. Use the Active Code window below or this |repl link| to have yertle draw the following shapes using loops. We encourage you to work in pairs.
+In the last exercise, you used a for-loop to have the turtle draw a square. Use the Active Code window below to have yertle draw the following shapes using loops. We encourage you to work in pairs. If the turtle code is too slow in the Active Code window, try it in |JuiceMind| or |replit| or download the files |github| to use in your own IDE.
-1. Have yertle draw an equilateral triangle using a loop. How many times should the loop run? Remember that it ran 4 times for a square, so how many for a triangle? What angle should you use for the turns? One way to figure this out is to notice that to complete a shape, all the exterior angles should add up to 360 degrees. So, for a square 4x90 = 360.
+1. Have yertle draw an equilateral triangle using a loop. How many times should the loop run? Remember that it ran 4 times for a square, so how many for a triangle? What angle should you use for the turns? One way to figure this out is to notice that to complete a shape, all the exterior angles should add up to 360 degrees. So, for a square 4x90 = 360.
2. Have yertle draw a pentagon using a loop. A pentagon has 5 sides. What external angle should you use for the turns? Remember they have to add up to 360 degrees.
-3. Create a variable n that holds the number of sides for any polygon, and use n in your loop. Can you have the loop draw a variety of shapes by just changing the value of the variable n? The power of abstraction! Can you draw a 9 sided nonagon? (Note that if the turtle runs into walls, it stays there and will mess up the shape, so you may have to move the turtle or go forward smaller amounts).
+3. Create a variable n that holds the number of sides for any polygon, and use n in your loop for the sides and to calculate the angle to turn. Can you have the loop draw a variety of shapes by just changing the value of the variable n? The power of abstraction! Can you draw a 9 sided nonagon? (Note that if the turtle runs into walls, it stays there and will mess up the shape, so you may have to move the turtle or go forward smaller amounts).
.. activecode:: challenge4-2-TurtleLoopShapes
:language: java
:autograde: unittest
:datafile: turtleClasses.jar
- Use a for-loop to draw a triangle. Then, change it to a pentagon. Then change it to draw any polygon using a variable n that holds the number of sides. Note that the angles in the turns have to add up to 360.
+ Use a for-loop to draw a triangle. Then, change it to a pentagon. Then change it to draw any polygon using a variable n that holds the number of sides. Note that the angles in the turns have to add up to 360. The autograder only checks one shape at a time, so comment out the code for one shape before starting on the next.
~~~~
- import java.util.*;
import java.awt.*;
+ import java.util.*;
public class TurtleDrawShapes
{
- public static void main(String[] args)
- {
- World world = new World(400,400);
- Turtle yertle = new Turtle(world);
- yertle.penUp(); // move a little to the left
- yertle.moveTo(100,200);
- yertle.penDown();
- yertle.setColor(Color.blue);
-
- // Add your loop here!
- yertle.forward(100);
- yertle.turn(90);
-
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(400, 400);
+ Turtle yertle = new Turtle(world);
+ yertle.penUp(); // move a little to the left
+ yertle.moveTo(100, 200);
+ yertle.penDown();
+ yertle.setColor(Color.blue);
+
+ // Add your loop here!
+ yertle.forward(100);
+ yertle.turn(90);
+
+ world.show(true);
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("TurtleDrawShapes");
}
@Test
public void test1()
{
- String target = "for (int * = *; * ? *; *~)";
- boolean passed = checkCodeContains("for loop", target);
- assertTrue(passed);
+ String target = "for (int * = *; * ? *; *~)";
+ boolean passed = checkCodeContainsRegex("for loop", target);
+ assertTrue(passed);
}
@Test
@@ -573,7 +582,12 @@ In the last exercise, you used a for-loop to have the turtle draw a square. Use
boolean passed = count == 1;
- passed = getResults("1 forward(...)", "" + count + " forward(...)", "Should only need forward() once", passed);
+ passed =
+ getResults(
+ "1 forward(...)",
+ "" + count + " forward(...)",
+ "Should only need forward() once",
+ passed);
assertTrue(passed);
}
@@ -587,7 +601,12 @@ In the last exercise, you used a for-loop to have the turtle draw a square. Use
boolean passed = count == 1;
- passed = getResults("1 turn(...)", "" + count + " turn(...)", "Should only need turn(...) once", passed);
+ passed =
+ getResults(
+ "1 turn(...)",
+ "" + count + " turn(...)",
+ "Should only need turn(...) once",
+ passed);
assertTrue(passed);
}
@@ -611,16 +630,14 @@ In the last exercise, you used a for-loop to have the turtle draw a square. Use
String code = getCode();
String test = "360/n";
- int count = countOccurences(code.replaceAll(" ",""), test);
+ int count = countOccurences(code.replaceAll(" ", ""), test);
boolean passed = count == 1;
passed = getResults("true", "" + passed, "Calculates angle correctly using n", passed);
assertTrue(passed);
}
}
-
-
-
+
Summary
-------
@@ -633,3 +650,111 @@ Summary
- A for loop can be rewritten into an equivalent while loop and vice versa.
+AP Practice
+------------
+
+.. mchoice:: AP4-2-1
+ :practice: T
+
+ Consider the following code segment.
+
+ .. code-block:: java
+
+ int count = 0, sum = 0;
+ while (count <= 6)
+ {
+ count++;
+ if (count % 2 == 0)
+ {
+ sum += count;
+ }
+ }
+ System.out.println(sum);
+
+ Which of the following code segments will produce the same output as the code segment above?
+
+ .. code-block:: java
+
+ I. int sum = 0;
+ for(int count = 0; count <= 6; count++)
+ {
+ count++;
+ if (count % 2 == 0)
+ {
+ sum += count;
+ }
+ }
+ System.out.println(sum);
+
+ II. int sum = 0;
+ for(int i = 0; i <= 6; i += 2)
+ {
+ sum += i;
+ }
+ System.out.println(sum);
+
+ III. int sum = 0;
+ for(int j = 7; j > 1; j--)
+ {
+ if (j % 2 == 0)
+ {
+ sum += j;
+ }
+ }
+ System.out.println(sum);
+
+ - I and II only
+
+ - Note that I has an extra count++ at the beginning of the loop body that should be deleted.
+
+ - II and III only
+
+ + Correct! In the II, the loop counter increments by 2's making sure it visits only even numbers and III generates the same sum but backwards.
+
+ - I and III only
+
+ - Note that I has an extra count++ at the beginning of the loop body that should be deleted.
+
+ - III only
+
+ - This is partially correct.
+
+ - I, II, and III
+
+ - Note that I has an extra count++ at the beginning of the loop body that should be deleted.
+
+.. mchoice:: AP4-2-2
+ :practice: T
+
+ Consider the following code segment.
+
+ .. code-block:: java
+
+ int result = 1;
+ for(int i = 3; i < 6; i += 2)
+ {
+ result *= i;
+ }
+ System.out.println(result);
+
+ Which of the following best explains how changing the for loop header to ``for (int i = 4; i <= 6; i += 2)`` affects the output of the code segment?
+
+ - The output of the code segment will be unchanged.
+
+ - One will multiply odd numbers and the other even numbers.
+
+ - The output will be the same, but the new loop will iterate more times.
+
+ - One will multiply odd numbers and the other even numbers.
+
+ - The output will be different, but both versions of the loop will iterate two times.
+
+ + Correct! One will multiply 3*5 and the other 4*6.
+
+ - The output will be different, and the new loop will iterate more times.
+
+ - The output is different but they both would iterate 2 times.
+
+ - This will cause an error.
+
+ - It will not cause an error.
diff --git a/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst b/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst
index c97d5019c..6cd7809d0 100644
--- a/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst
+++ b/_sources/Unit4-Iteration/topic-4-3-strings-loops.rst
@@ -1,40 +1,26 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 4-3-
:start: 1
-
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
-.. |AP CS A Reference Sheet| raw:: html
-
- AP CS A Java Quick Reference Sheet
+
+
+.. |AP CSA Reference Sheet| raw:: html
+
+ AP CSA Java Quick Reference Sheet
+
+|Time90|
Loops and Strings
=================
-.. index::
- single: string processing
- pair: string; loop
-
-Loops are often used for **String Traversals** or **String Processing** where the code steps through a string character by character. In lesson 2.6 and 2.7, we learned to use String objects and built-in string methods to process strings. In this lesson, we will write our own loops to process strings.
+.. index::
+ single: string processing
+ pair: string; loop
+
+Loops are often used for **String Traversals** or **String Processing** where the code steps through a string character by character. In lesson 2.6 and 2.7, we learned to use String objects and built-in string methods to process strings. In this lesson, we will write our own loops to process strings.
-Remember that strings are a sequence of characters where each character is at a position or **index** starting at 0.
+Remember that strings are a sequence of characters where each character is at a position or **index** starting at 0.
.. figure:: Figures/stringIndicies.png
:width: 500px
@@ -48,13 +34,13 @@ Remember that strings are a sequence of characters where each character is at a
The first character in a Java String is at index 0 and the last characters is at **length()** - 1. So loops processing Strings should start at 0!
-The String methods (covered in lesson 2.7 and given in the |AP CS A Reference Sheet|) that are most often used to process strings are:
+The String methods (covered in lesson 2.7 and given in the |AP CSA Reference Sheet|) that are most often used to process strings are:
-- **int length()** : returns the number of characters in a String object.
-
-- **int indexOf(String str)** : returns the index of the first occurrence of str; returns -1 if not found.
+- **int length()** : returns the number of characters in a String object.
-- **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to – 1). Note that s.substring(i,i+1) returns the character at index i.
+- **int indexOf(String str)** : returns the index of the first occurrence of ``str`` or -1 if ``str`` is not found.
+
+- **String substring(int from, int to)** : returns the substring beginning at index from and ending at index (to – 1). Note that s.substring(i,i+1) returns the character at index i.
- **String substring(int from)** : returns substring(from, length()).
@@ -71,9 +57,9 @@ The String methods (covered in lesson 2.7 and given in the |AP CS A Reference Sh
While Find and Replace Loop
---------------------------
-A while loop can be used with the String indexOf method to find certain characters in a string and process them, usually using the substring method.
+A while loop can be used with the ``String`` ``indexOf`` method to find certain characters in a string and process them, usually using the ``substring`` method.
-.. code-block:: java
+.. code-block:: java
String s = "example";
int i = 0;
@@ -90,7 +76,7 @@ A while loop can be used with the String indexOf method to find certain characte
The example in the mixed up code below finds and removes all the letter a's in a string. You can watch it in action in this |Java visualizer1|.
|Exercise| **Check Your Understanding**
-
+
.. parsonsprob:: removeA
:numbered: left
@@ -103,121 +89,131 @@ The example in the mixed up code below finds and removes all the letter a's in a
public static void main(String[] args)
{
=====
- String s = "are apples tasty without an a?";
+ String s = "are apples tasty without an a?";
int index = 0;
System.out.println("Original string: " + s);
=====
// while there is an a in s
while (s.indexOf("a") >= 0)
{
- =====
+ =====
// Find the next index for an a
index = s.indexOf("a");
- =====
- // Remove the a at index by concatenating
+ =====
+ // Remove the a at index by concatenating
// substring up to index and then rest of the string.
- s = s.substring(0,index) +
+ s = s.substring(0,index) +
s.substring(index+1);
- =====
- } // end loop
+ =====
+ } // end loop
=====
System.out.println("String with a's removed:" + s);
=====
} // end method
-
-
+
+
Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using the number 1 for the letter l. Try the code below (and in the |Java visualizer|) to clean up scanning mistakes like this.
|CodingEx| **Coding Exercise**
-The following code loops through a string replacing all 1's with l's. Trace through the code below with a partner and explain how it works on the given message. You can run it line by line in the |Java visualizer|. Note that indexOf here can work repeatedly to find the next occurrence of a 1 because they are replaced as soon as they are found.
+The following code loops through a string replacing all 1's with l's. Trace through the code below with a partner and explain how it works on the given message. You can run it line by line in the |Java visualizer|. Note that ``indexOf`` here can work repeatedly to find the next occurrence of a 1 because they are replaced as soon as they are found.
.. activecode:: lclw1
:language: java
:autograde: unittest
-
+
Change the code to add code for a counter variable to count the number of 1's replaced in the message and print it out. Change the message to have more mistakes with 1's to test it.
~~~~
public class FindAndReplace
{
- public static void main(String[] args)
- {
- String message = "Have a 1ong and happy 1ife";
- int index = 0;
-
- // while more 1's in the message
- while (message.indexOf("1") >= 0)
- {
- // Find the next index for 1
- index = message.indexOf("1");
- System.out.println("Found a 1 at index: " + index);
- // Replace the 1 with a l at index by concatenating substring up to index and then the rest of the string.
- String firstpart = message.substring(0,index);
- String lastpart = message.substring(index+1);
- message = firstpart + "l" + lastpart;
- System.out.println("Replaced 1 with l at index " + index);
- System.out.println("The message is currently " + message + " but we aren't done looping yet!");
- }
- System.out.println("Cleaned text: " + message);
- }
+ public static void main(String[] args)
+ {
+ String message = "Have a 1ong and happy 1ife";
+ int index = 0;
+
+ // while more 1's in the message
+ while (message.indexOf("1") >= 0)
+ {
+ // Find the next index for 1
+ index = message.indexOf("1");
+ System.out.println("Found a 1 at index: " + index);
+ // Replace the 1 with a l at index by concatenating substring up to
+ // index and then the rest of the string.
+ String firstpart = message.substring(0, index);
+ String lastpart = message.substring(index + 1);
+ message = firstpart + "l" + lastpart;
+ System.out.println("Replaced 1 with l at index " + index);
+ System.out.println(
+ "The message is currently "
+ + message
+ + " but we aren't done looping yet!");
+ }
+ System.out.println("Cleaned text: " + message);
+ }
}
+
====
// Test for Lesson 4.3.1 - While Loop FindAndReplace lclw1
- import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
+ import static org.junit.Assert.*;
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("FindAndReplace");
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("FindAndReplace");
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main").trim();
+ String expect =
+ "Found a 1 at index: 7\n"
+ + "Replaced 1 with l at index 7\n"
+ + "The message is currently Have a long and happy 1ife but we aren't done"
+ + " looping yet!\n"
+ + "Found a 1 at index: 22\n"
+ + "Replaced 1 with l at index 22\n"
+ + "The message is currently Have a long and happy life but we aren't done"
+ + " looping yet!\n"
+ + "Cleaned text: Have a long and happy life\n";
+
+ boolean pass = !output.equals(expect.trim());
+
+ boolean passed = getResults(expect, output, "Output should be different", pass);
+ assertTrue(passed);
+ }
+ }
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main").trim();
- String expect = "Found a 1 at index: 7\n" +
- "Replaced 1 with l at index 7\n" +
- "The message is currently Have a long and happy 1ife but we aren't done looping yet!\n" +
- "Found a 1 at index: 22\n" +
- "Replaced 1 with l at index 22\n" +
- "The message is currently Have a long and happy life but we aren't done looping yet!\n" +
- "Cleaned text: Have a long and happy life\n";
-
- boolean pass = !output.equals(expect.trim());
-
- boolean passed = getResults(expect, output, "Output should be different", pass);
- assertTrue(passed);
- }
- }
-
-
For Loops: Reverse String
--------------------------
-For-loops can also be used to process strings, especially in situations where you know you will visit every character.
+``for`` loops can also be used to process strings, especially in situations where you know you will visit every character.
.. note::
- While loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run. For loops are used when you know you want to visit every character.
+ ``while`` loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run. ``for`` loops are used when you know you want to visit every character.
-For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character.
+``for`` loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character.
-.. code-block:: java
+.. code-block:: java
String s = "example";
- // loop through the string from 0 to length
- for(int i=0; i < s.length(); i++)
+ // loop through the string from 0 to length
+ for(int i=0; i < s.length(); i++)
{
- String ithLetter = s.substring(i,i+1);
+ String ithLetter = s.substring(i,i+1);
// Process the string at that index
...
}
|Exercise| **Check Your Understanding**
-
+
.. parsonsprob:: countEs
:numbered: left
@@ -233,77 +229,95 @@ For loops with strings usually start at 0 and use the string's length() for the
String message = "e is the most frequent English letter.";
int count = 0;
=====
- for(int i=0; i < message.length(); i++)
+ for(int i=0; i < message.length(); i++)
{
=====
if (message.substring(i,i+1).equalsIgnoreCase("e"))
=====
count++;
- =====
+ =====
}
- =====
- System.out.println(count);
+ =====
+ System.out.println(count);
=====
}
-
-
-Here is a for-loop that creates a new string that reverses the string s. We start with a blank string sReversed and build up our reversed string in that variable by copying in characters from the string s. You can also run this code in this |Java visualizer link| or by clicking on the Code Lens button below.
+
+
+Here is a ``for`` loop that creates a new string that reverses the string ``s``. We start with a blank string ``sReversed`` and build up our reversed string in that variable by copying in characters from the string ``s``. You can also run this code in this |Java visualizer link| or by clicking on the Code Lens button below.
.. |Java visualizer link| raw:: html
Java visualizer link
-
+
|CodingEx| **Coding Exercise**
.. activecode:: reverseString
:language: java
:autograde: unittest
-
+
What would happen if you started the loop at 1 instead? What would happen if you used <= instead of What would happen if you changed the order in which you added the ithLetter in line 12?
~~~~
public class ReverseString
{
- public static void main(String[] args)
- {
- String s = "Hello";
- String sReversed = "";
- String ithLetter;
-
- for(int i=0; i < s.length(); i++) {
- ithLetter = s.substring(i,i+1);
- // add the letter at index i to what's already reversed.
- sReversed = ithLetter + sReversed;
- }
- System.out.println(s + " reversed is " + sReversed);
- }
- }
+ public static void main(String[] args)
+ {
+ String s = "Hello";
+ String sReversed = "";
+ String ithLetter;
+
+ for (int i = 0; i < s.length(); i++)
+ {
+ ithLetter = s.substring(i, i + 1);
+ // add the letter at index i to what's already reversed.
+ sReversed = ithLetter + sReversed;
+ }
+ System.out.println(s + " reversed is " + sReversed);
+ }
+ }
+
====
// Test for Lesson 4.3 - ReverseString
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("ReverseString");
}
@Test
public void testMain() throws IOException
{
- String origCode = "public class ReverseString { public static void main(String[] args) { String s = \"Hello\"; String sReversed = \"\"; String ithLetter; for(int i=0; i < s.length(); i++) { ithLetter = s.substring(i,i+1); // add the letter at index i to what's already reversed. sReversed = ithLetter + sReversed; } System.out.println(s + \" reversed is \" + sReversed); } }";
+ String origCode =
+ "public class ReverseString\n"
+ + "{\n"
+ + " public static void main(String[] args)\n"
+ + " {\n"
+ + " String s = \"Hello\";\n"
+ + " String sReversed = \"\";\n"
+ + " String ithLetter;\n\n"
+ + " for(int i=0; i < s.length(); i++) {\n"
+ + " ithLetter = s.substring(i,i+1);\n"
+ + " // add the letter at index i to what's already reversed.\n"
+ + " sReversed = ithLetter + sReversed;\n"
+ + " }\n"
+ + " System.out.println(s + \" reversed is \" + sReversed);\n"
+ + " }\n"
+ + " }\n\n";
boolean passed = codeChanged(origCode);
assertTrue(passed);
}
}
-
-
|Groupwork| Programming Challenge : String Replacement Cats and Dogs
---------------------------------------------------------------------
@@ -311,91 +325,90 @@ Here is a for-loop that creates a new string that reverses the string s. We sta
:width: 150
:align: left
:alt: Cat or Dog
-
-Are you a cat person or a dog person? The code below prints a nice message about cats, but if you're a dog person, you might not agree.
-1. Write some code below that changes every occurrence of "cat" to "dog" in the message. This code will be more like the first program in this lesson where we replaced 1's with l's.
+Are you a cat person or a dog person? The code below prints a nice message about cats, but if you're a dog person, you might not agree.
+
+1. Write some code below that changes every occurrence of "cat" to "dog" in the message. This code will be more like the first program in this lesson where we replaced 1's with l's.
2. (Optional - not autograded) add a counter to count the number of replacements and print it out.
-3. (Optional - challenging and not autograded) What if you like both cats and dogs? After you replace "cat" with "dog", add another loop that looks for the word "dogs" and adds " and cats" to it. Do not replace "dog", just replace "dogs". This will just replace the first sentence in the example below but you can add other sentences to test. For this loop, you will need to use a special version of indexOf that searches from a given index, so that you don't end up with an infinite loop that keeps finding the first "dogs". Make sure you add a variable **fromIndex** that is initialized to 0 and that is changed each time through the loop to skip over the last word that was found.
+3. (Optional - challenging and not autograded) What if you like both cats and dogs? After you replace "cat" with "dog", add another loop that looks for the word "dogs" and adds " and cats" to it. Do not replace "dog", just replace "dogs". This will just replace the first sentence in the example below but you can add other sentences to test. For this loop, you will need to use a special version of ``indexOf`` that searches from a given index, so that you don't end up with an infinite loop that keeps finding the first "dogs". Make sure you add a variable **fromIndex** that is initialized to 0 and that is changed each time through the loop to skip over the last word that was found.
- - **int indexOf(String target, int fromIndex)** searches left-to-right for the target substring, but starts the search at the given fromIndex. You are not required to know this version of indexOf for the AP CS A exam, but you can use it (and any valid Java code) in the Free Response Questions.
+ - **int indexOf(String target, int fromIndex)** searches left-to-right for the target substring, but starts the search at the given fromIndex. You are not required to know this version of indexOf for the AP CSA exam, but you can use it (and any valid Java code) in the Free Response Questions.
.. activecode:: challenge4-3-string-replace
:language: java
:autograde: unittest
:practice: T
-
+
Write a while loop that replaces every occurrence of "cat" in the message with "dog" using the indexOf and substring methods.
~~~~
public class ChallengeReplace
{
- public static void main(String[] args)
- {
- String message = "I love cats! I have a cat named Coco. My cat's very smart!";
-
- // Write a loop here that replaces every occurrence of "cat"
- // in the message with "dog", using indexOf and substring.
-
-
-
- System.out.println(message);
- }
- }
- ====
- // Test Code for Lesson 4.3.3 - String Replacement - ChallengeReplace
+ public static void main(String[] args)
+ {
+ String message =
+ "I love cats! I have a cat named Coco. My cat's very smart!";
- import static org.junit.Assert.*;
-
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
+ // Write a loop here that replaces every occurrence of "cat"
+ // in the message with "dog", using indexOf and substring.
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("ChallengeReplace");
- }
+ System.out.println(message);
+ }
+ }
- @Test
- public void test1() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "I love cats! I have a cat named Coco. My cat's very smart!".replaceAll("cat","dog");
+ ====
+ // Test Code for Lesson 4.3.3 - String Replacement - ChallengeReplace
- boolean passed = getResults(expect, output, "Running main");
- assertTrue(passed);
- }
+ import static org.junit.Assert.*;
- @Test
- public void testWhile() throws IOException
- {
- String target = "while(";
- boolean passed = checkCodeContains("while loop", target);
- assertTrue(passed);
- }
-
- @Test
- public void testSubString()
- {
- String target = "substring(";
- boolean passed = checkCodeContains("substring", target);
- assertTrue(passed);
- }
-
- @Test
- public void testReplace() throws IOException
- {
- String target = ".replace";
- boolean passed = checkCodeNotContains("shortcut replace", target);
- assertTrue(passed);
- }
+ import org.junit.Test;
- }
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("ChallengeReplace");
+ }
+
+ @Test
+ public void test1() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "I love cats! I have a cat named Coco. My cat's very smart!"
+ .replaceAll("cat", "dog");
+
+ boolean passed = getResults(expect, output, "Running main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testWhile() throws IOException
+ {
+ String target = "while(";
+ boolean passed = checkCodeContains("while loop", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testSubString()
+ {
+ String target = "substring(";
+ boolean passed = checkCodeContains("substring", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testReplace() throws IOException
+ {
+ String target = ".replace";
+ boolean passed = checkCodeNotContains("shortcut replace", target);
+ assertTrue(passed);
+ }
+ }
Summary
---------
@@ -408,4 +421,4 @@ There are standard algorithms that utilize String traversals to:
* Determine the number of substrings that meet specific criteria
* Create a new string with the characters reversed
-For more practice with string processing, see the Free Response Question in the Practice and Summary section of this unit.
\ No newline at end of file
+For more practice with string processing, see the Free Response Question in the Practice and Summary section of this unit.
diff --git a/_sources/Unit4-Iteration/topic-4-4-nested-loops.rst b/_sources/Unit4-Iteration/topic-4-4-nested-loops.rst
index 316826050..93437203e 100644
--- a/_sources/Unit4-Iteration/topic-4-4-nested-loops.rst
+++ b/_sources/Unit4-Iteration/topic-4-4-nested-loops.rst
@@ -1,42 +1,27 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 4-4-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-.. turtle snowflake patterns
+
+|Time90|
Nested For Loops
================
-.. index::
- single: nested for loop
- pair: loop; nested
+.. index::
+ single: nested for loop
+ pair: loop; nested
-A **nested loop** has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop is runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.
+A **nested loop** has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.
.. figure:: Figures/nestedloops.png
:width: 350px
:align: center
:figclass: align-center
-
+
Figure 1: Nested Loops
-
+
.. |Java visualizer| raw:: html
Java visualizer
@@ -48,55 +33,51 @@ What does the following code print out? Watch the code run in the |Java visuali
.. activecode:: lcfcnl1
:language: java
- :autograde: unittest
+ :autograde: unittest
:practice: T
-
- Can you change the code to be a 10x8 rectangle? Try replacing line 10 with this print statement to see the rows and columns: System.out.print(row + "-" + col + " ");
+
+ Can you change the code to print a rectangle with 10 rows and 8 columns of stars? You can also try replacing line 10 with this print statement to see the rows and columns: ``System.out.print(row + "-" + col + " ");``
~~~~
public class NestedLoops
{
- public static void main(String[] args)
- {
- for (int row = 1; row <= 3; row++)
- {
- for (int col = 1; col <= 5; col++)
- {
- System.out.print("*");
- }
- System.out.println();
- }
- }
+ public static void main(String[] args)
+ {
+ for (int row = 1; row <= 3; row++)
+ {
+ for (int col = 1; col <= 5; col++)
+ {
+ System.out.print("*");
+ }
+ System.out.println();
+ }
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("NestedLoops");
- }
+ import org.junit.*;
- @Test
- public void test1()
- {
- String orig = "public class NestedLoops\n{\n\n public static void main(String[] args)\n {\n for (int row = 1; row <= 3; row++)\n {\n for (int col = 1; col <= 5; col++)\n {\n System.out.print(\"*\");\n }\n System.out.println();\n }\n }\n}\n";
+ import java.io.*;
- boolean passed = codeChanged(orig);
- assertTrue(passed);
- }
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("NestedLoops");
+ }
+
+ @Test
+ public void test2()
+ {
+ boolean passed =
+ checkCodeContains("10 rows", "row <= 10")
+ && checkCodeContains("8 columns", "col <= 8");
+ assertTrue(passed);
+ }
+ }
- @Test
- public void test2()
- {
- boolean passed = checkCodeContains("10 rows","row <= 10")
- && checkCodeContains("8 columns","col <= 8");
- assertTrue(passed);
- }
- }
-
|Exercise| **Check your understanding**
.. mchoice:: nested1
@@ -106,24 +87,24 @@ What does the following code print out? Watch the code run in the |Java visuali
:answer_c: A rectangle of 6 rows with 5 stars per row.
:answer_d: A rectangle of 6 rows with 4 stars per row.
:correct: c
- :feedback_a: This would be true if i was initialized to 0.
+ :feedback_a: This would be true if i was initialized to 0.
:feedback_b: This would be true if i was initialized to 0 and the inner loop continued while y < 5.
- :feedback_c: The outer loop runs from 1 up to 7 but not including 7 so there are 6 rows and the inner loop runs 1 to 5 times including 5 so there are 5 columns.
- :feedback_d: This would be true if the inner loop continued while y < 5.
+ :feedback_c: The outer loop runs from 1 up to 7 but not including 7 so there are 6 rows and the inner loop runs 1 to 5 times including 5 so there are 5 columns.
+ :feedback_d: This would be true if the inner loop continued while y < 5.
What does the following code print?
-
- .. code-block:: java
- for (int i = 1; i < 7; i++)
- {
+ .. code-block:: java
+
+ for (int i = 1; i < 7; i++)
+ {
for (int y = 1; y <= 5; y++)
{
System.out.print("*");
}
System.out.println();
}
-
+
.. mchoice:: nested2
:practice: T
:answer_a: A rectangle of 4 rows with 3 star per row.
@@ -131,17 +112,17 @@ What does the following code print out? Watch the code run in the |Java visuali
:answer_c: A rectangle of 4 rows with 1 star per row.
:answer_d: The loops have errors.
:correct: b
- :feedback_a: This would be true if i was initialized to 1 or ended at 4.
- :feedback_b: Yes, the outer loop runs from 0 up to 5 but not including 5 so there are 5 rows and the inner loop runs from 3 down to 1 so 3 times.
- :feedback_c: The inner loop runs 3 times when j is 3, 2, and then 1, so there are 3 stars per row.
- :feedback_d: Try the code in an Active Code window and you will see that it does run.
+ :feedback_a: This would be true if i was initialized to 1 or ended at 4.
+ :feedback_b: Yes, the outer loop runs from 0 up to 5 but not including 5 so there are 5 rows and the inner loop runs from 3 down to 1 so 3 times.
+ :feedback_c: The inner loop runs 3 times when j is 3, 2, and then 1, so there are 3 stars per row.
+ :feedback_d: Try the code in an Active Code window and you will see that it does run.
What does the following code print?
-
- .. code-block:: java
- for (int i = 0; i < 5; i++)
- {
+ .. code-block:: java
+
+ for (int i = 0; i < 5; i++)
+ {
for (int j = 3; j >= 1; j--)
{
System.out.print("*");
@@ -155,20 +136,20 @@ What does the following code print out? Watch the code run in the |Java visuali
:adaptive:
:noindent:
- The main method in the following class should print 10 rows with 5 * in each row. But, the blocks have been mixed up and include one extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
i?
- :feedback_b: The outer loop executes 7-3+1=5 times and the inner 4-1+1=4 so this will print 5 * 4 = 20 stars.
- :feedback_c: This would be true if the outer loop executed 6 times such as if it was i <= 8.
- :feedback_d: This would be true if the inner loop executed 5 times such as if it was y <= 5.
-
+ :feedback_a: This would be true if the outer loop executed 8 times and the inner 5 times, but what is the initial value of i?
+ :feedback_b: The outer loop executes 7-3+1=5 times and the inner 4-1+1=4 so this will print 5 * 4 = 20 stars.
+ :feedback_c: This would be true if the outer loop executed 6 times such as if it was i <= 8.
+ :feedback_d: This would be true if the inner loop executed 5 times such as if it was y <= 5.
+
How many times does the following code print a ``*``?
-
- .. code-block:: java
- for (int i = 3; i < 8; i++)
- {
+ .. code-block:: java
+
+ for (int i = 3; i < 8; i++)
+ {
for (int y = 1; y < 5; y++)
{
System.out.print("*");
}
System.out.println();
}
-
+
.. mchoice:: qln_6_2
:practice: T
:answer_a: A rectangle of 8 rows with 5 stars per row.
@@ -307,24 +393,24 @@ Do the following exercises in your group. Make sure you draw the trace tables ke
:answer_c: A rectangle of 6 rows with 5 stars per row.
:answer_d: A rectangle of 6 rows with 4 stars per row.
:correct: c
- :feedback_a: This would be true if i was initialized to 0.
+ :feedback_a: This would be true if i was initialized to 0.
:feedback_b: This would be true if i was initialized to 0 and the inner loop continued while y < 5.
- :feedback_c: The outer loop executes 8-2+1=6 times so there are 6 rows and the inner loop executes 5-1+1=5 times so there are 5 columns.
- :feedback_d: This would be true if the inner loop continued while y < 5.
+ :feedback_c: The outer loop executes 8-2+1=6 times so there are 6 rows and the inner loop executes 5-1+1=5 times so there are 5 columns.
+ :feedback_d: This would be true if the inner loop continued while y < 5.
What does the following code print?
-
- .. code-block:: java
- for (int i = 2; i < 8; i++)
- {
+ .. code-block:: java
+
+ for (int i = 2; i < 8; i++)
+ {
for (int y = 1; y <= 5; y++)
{
System.out.print("*");
}
System.out.println();
}
-
+
.. mchoice:: qln_6_3
:practice: T
:answer_a: A rectangle of 9 rows and 5 stars per row.
@@ -332,24 +418,24 @@ Do the following exercises in your group. Make sure you draw the trace tables ke
:answer_c: A rectangle of 7 rows and 5 stars per row.
:answer_d: A rectangle of 7 rows and 6 stars per row.
:correct: d
- :feedback_a: Did you notice what i was initialized to?
- :feedback_b: It would print 6 rows if it was i < 9.
- :feedback_c: It would print 5 stars per row if it was j > 1.
- :feedback_d: The outer loop executes 9 - 3 + 1 = 7 times and the inner 6 - 1 + 1 = 6 times.
+ :feedback_a: Did you notice what i was initialized to?
+ :feedback_b: It would print 6 rows if it was i < 9.
+ :feedback_c: It would print 5 stars per row if it was j > 1.
+ :feedback_d: The outer loop executes 9 - 3 + 1 = 7 times and the inner 6 - 1 + 1 = 6 times.
What does the following print?
-
- .. code-block:: java
- for (int i = 3; i <= 9; i++)
- {
+ .. code-block:: java
+
+ for (int i = 3; i <= 9; i++)
+ {
for (int j = 6; j > 0; j--)
{
System.out.print("*");
}
System.out.println();
}
-
+
.. mchoice:: qln4
:practice: T
@@ -358,14 +444,14 @@ Do the following exercises in your group. Make sure you draw the trace tables ke
:answer_c: 10
:answer_d: 8
:correct: a
- :feedback_a: The outer loop executes 4-0+1=5 times and the inner loop 2-0+1=3, so hi is printed 5*3 = 15 times
- :feedback_b: The outer loop runs 5 times for i = 0, 1, 2, 3, 4.
+ :feedback_a: The outer loop executes 4-0+1=5 times and the inner loop 2-0+1=3, so hi is printed 5*3 = 15 times
+ :feedback_b: The outer loop runs 5 times for i = 0, 1, 2, 3, 4.
:feedback_c: The inner loop runs 3 times for j = 0, 1, 2.
:feedback_d: The outer loop runs 5 times for i = 0, 1, 2, 3, 4.
Consider the following code segment. How many times is the string "Hi!" printed as a result of executing the code segment?
-
- .. code-block:: java
+
+ .. code-block:: java
int i = 0;
while (i <= 4)
@@ -384,10 +470,26 @@ Do the following exercises in your group. Make sure you draw the trace tables ke
Summary
-------
-- A trace table can be used to keep track of the variables and their values throughout each iteration of the loop.
+- A trace table can be used to keep track of the variables and their values throughout each iteration of the loop.
- We can determine the number of times a code segment will execute with a **statement execution count**. This is called **run-time analysis**.
-- The number of times a loop executes can be calculated by (largestValue - smallestValue + 1) where these are the largest and smallest values of the loop counter variable possible in the body of the loop.
+- The number of times a loop executes can be calculated by ``largestValue - smallestValue + 1`` where these are the largest and smallest values of the loop counter variable possible in the body of the loop.
+
+- The number of times a nested for-loop runs is the number of times the outer loop runs **times** the number of times the inner loop runs.
+
+
+Loop Analysis Game
+-------------------------
+
+.. |game| raw:: html
+
+ game
+
+
+Try the game below to practice loop analysis. Click on **Loops** and click on the number of times the loop runs. For an added challenge, try the check boxes for Backwards, Do While, and Nested. We encourage you to work in pairs and see how high a score you can get.
+
+.. raw:: html
-- The number of times a nested for-loop runs is the number of times the outer loop runs **times** the number of times the inner loop runs.
+
+
diff --git a/_sources/Unit4-Iteration/topic-4-6-group-mod.rst b/_sources/Unit4-Iteration/topic-4-6-group-mod.rst
new file mode 100644
index 000000000..fe8621767
--- /dev/null
+++ b/_sources/Unit4-Iteration/topic-4-6-group-mod.rst
@@ -0,0 +1,153 @@
+.. include:: ../common.rst
+
+.. qnum::
+ :prefix: 4-7-
+ :start: 1
+
+Group Work - Remainder Operator (%)
+========================================
+
+It is best to use a POGIL approach with the following. In POGIL students work
+in groups on activities and each member has an assigned role. For more information see `https://cspogil.org/Home * in each row. But, the blocks have been mixed up and include two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The main method in the following class should print 3 rows with 6 \*'s in each row. But, the blocks have been mixed up and include two extra blocks that aren't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
public class Test1
{
@@ -147,32 +152,36 @@ Try to solve each of the following. Click the *Check Me* button to check each so
public static void main(String[] args)
{
=====
- for (int x = 3; x > 0; x--) {
+ for (int x = 3; x > 0; x--)
+ {
=====
- for (int x = 0; x <= 3; x++) { #paired
+ for (int x = 0; x <= 3; x++)
+ { #paired
=====
- for (int y = 6; y > 0; y--) {
+ for (int y = 6; y > 0; y--)
+ {
=====
- for (int y = 0; y <= 6; y++) { #paired
+ for (int y = 0; y <= 6; y++)
+ { #paired
=====
- System.out.print("*");
+ System.out.print("*");
=====
}
=====
System.out.println();
=====
- }
+ }
}
}
-
+
.. parsonsprob:: ch6ex8muc
:numbered: left
:practice: T
:adaptive:
:noindent:
- The main method in the following class should print 1 (followed by a newline), then 22 (followed by a newline), and then 333 (followed by a newline). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The main method in the following class should print 1 (followed by a newline), then 22 (followed by a newline), and then 333 (followed by a newline). But, the blocks have been mixed up and include an extra block that isn't needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
public class Test1
{
@@ -180,28 +189,31 @@ Try to solve each of the following. Click the *Check Me* button to check each so
public static void main(String[] args)
{
=====
- for (int x = 1; x <= 3; x++) {
+ for (int x = 1; x <= 3; x++)
+ {
=====
- for (int x = 0; x < 3; x++) { #paired
+ for (int x = 0; x < 3; x++)
+ { #paired
=====
- for (int y = 0; y < x; y++) {
+ for (int y = 0; y < x; y++)
+ {
=====
System.out.print(x);
=====
}
- System.out.println();
+ System.out.println();
}
=====
}
}
-
+
.. parsonsprob:: ch6ex9muc
:numbered: left
:practice: T
:adaptive:
:noindent:
- The main method in the following class should print 11111, 22222, 33333, 44444, and 55555. But, the blocks have been mixed up and contain two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The main method in the following class should print 11111, 22222, 33333, 44444, and 55555. But, the blocks have been mixed up and contain two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
public class Test1
{
@@ -209,33 +221,36 @@ Try to solve each of the following. Click the *Check Me* button to check each so
public static void main(String[] args)
{
=====
- for (int x = 1; x <= 5; x++) {
+ for (int x = 1; x <= 5; x++)
+ {
=====
- for (int x = 1; x < 5; x++) { #paired
+ for (int x = 1; x < 5; x++)
+ { #paired
=====
- for (int y = 0; y < 5; y++) {
+ for (int y = 0; y < 5; y++)
+ {
=====
System.out.print(x);
=====
System.out.print(y); #paired
=====
} //end inner loop
- System.out.println();
+ System.out.println();
=====
} //end outer loop
=====
}
}
-
-
+
+
.. parsonsprob:: ch6ex10muc
:numbered: left
:practice: T
:adaptive:
:noindent:
- The main method in the following class should print 11111, 2222, 333, 44, 5. But, the blocks have been mixed up and include one extra block that isn't needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check Me button to check your solution.
+ The main method in the following class should print 11111, 2222, 333, 44, 5. But, the blocks have been mixed up and include one extra block that isn't needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.
-----
public class Test1
{
@@ -243,22 +258,105 @@ Try to solve each of the following. Click the *Check Me* button to check each so
public static void main(String[] args)
{
=====
- for (int x = 0; x < 5; x++) {
+ for (int x = 0; x < 5; x++)
+ {
=====
- for (int y = 5; y > x; y--) {
+ for (int y = 5; y > x; y--)
+ {
=====
System.out.print(x+1);
=====
System.out.print(x); #paired
=====
} //end inner loop
- System.out.println();
+ System.out.println();
=====
} //end outer loop
=====
}
}
-
+.. parsonsprob:: ch6ex11muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
-
+ The ``get_mid(str)`` method in the ``StringWorker`` class should return the
+ middle character if the string has an odd number of characters and the middle
+ two characters if the string has an even number of characters. For example,
+ ``get_mid("way")`` should return ``"a"`` and ``get_mid("away")`` should
+ return ``"wa"``.
+ -----
+ public class StringWorker
+ {
+ =====
+ public static String get_mid(String str)
+ {
+ =====
+ int str_len = str.length();
+ int mid = str_len / 2;
+ =====
+ /* if odd number of chars */
+ if (str_len % 2 == 1)
+ {
+ =====
+ return str.substring(mid, mid+1);
+ =====
+ }
+ =====
+ else
+ {
+ =====
+ return str.substring(mid-1, mid+1);
+ =====
+ }
+ =====
+ }
+ =====
+ }
+
+
+.. parsonsprob:: ch6ex12muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The ``ev_div(s, n)`` method in the ``NumWorker`` class should return the
+ number of digits in ``s`` (a string representation of a number) that are
+ evenly divisible by ``n``. For example, ``even_div('6892',3)`` should return
+ 2 since both 6 and 9 are evenly divisible by 3.
+ -----
+ public class NumWorker
+ {
+ =====
+ public static int ev_div(String s, int n)
+ {
+ =====
+ int c_num = 0;
+ String c_digit = "";
+ int count = 0;
+ =====
+ for (int i = 0; i < s.length(); i++)
+ {
+ =====
+ c_digit = s.substring(i, i+1);
+ =====
+ c_num = Integer.parseInt(c_digit);
+ =====
+ /* if is evely divisible by n */
+ if (c_num % n == 0)
+ {
+ =====
+ count += 1;
+ =====
+ }
+ =====
+ }
+ =====
+ return count;
+ =====
+ }
+ =====
+ }
diff --git a/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst b/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst
index 29ce039f8..492bc9b91 100644
--- a/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst
+++ b/_sources/Unit4-Iteration/topic-4-8-practice-coding.rst
@@ -1,22 +1,22 @@
.. qnum::
- :prefix: 4-6-5-
+ :prefix: 4-9-
:start: 1
-
+
Coding Practice with Loops
------------------------------------
.. tabbed:: ch6ex1
.. tab:: Question
-
+
.. activecode:: ch6ex1q
:language: java
:autograde: unittest
:practice: T
-
- Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 1 (inclusive).
+
+ Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 1 (inclusive).
~~~~
- public class Test
+ public class Test1
{
public static void main(String[] args)
{
@@ -28,114 +28,114 @@ Coding Practice with Loops
}
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "5\n4\n3\n2\n1\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testForLoop() throws IOException
- {
- String target = "for(int x = 5;";
- boolean passed = checkCodeContains("for loop", target);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "5\n4\n3\n2\n1\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ @Test
+ public void testForLoop() throws IOException
+ {
+ String target = "for(int * = 5;";
+ boolean passed = checkCodeContains("for loop", target);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
+
.. activecode:: ch6ex1a
:language: java
:optional:
-
+
Answer: In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below.
~~~~
- public class Test
+ public class Test1
{
public static void main(String[] args)
{
- for (int x = 5; x > 0; x = x - 1)
- System.out.println(x);
+ for (int x = 5; x > 0; x = x - 1) System.out.println(x);
}
}
-
- .. tab:: Discussion
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex1d
-
+
.. tabbed:: ch6ex2
.. tab:: Question
-
+
.. activecode:: ch6ex2q
:language: java
:autograde: unittest
:practice: T
-
+
Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 1 to 10 (inclusive).
~~~~
- public class Test
+ public class Test1
{
public static void main(String[] args)
{
- for (int x = 1; x <= 10; x++)
- System.out.println(x);
+ for (int x = 1; x <= 10; x++) System.out.println(x);
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
- //import java.util.regex.*;
- /* Do NOT change Main or CodeTestHelper.java. */
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testForLoop() throws IOException
- {
- String target = "while (x";
- boolean passed = checkCodeContains("while loop", target);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ // import java.util.regex.*;
+ /* Do NOT change Main or CodeTestHelper.java. */
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop() throws IOException
+ {
+ String target = "while (";
+ boolean passed = checkCodeContains("while loop", target);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
-
+
+ Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
+
.. activecode:: ch6ex2a
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -146,25 +146,25 @@ Coding Practice with Loops
System.out.println(x);
x++;
}
- }
+ }
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex2d
-
+
.. tabbed:: ch6ex3
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex3q
:language: java
:autograde: unittest
:practice: T
-
- Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 15 (inclusive).
+
+ Rewrite the following code so that it uses a ``for`` loop instead of a ``while`` loop to print out all the integers from 5 to 15 (inclusive).
~~~~
public class Test1
{
@@ -178,40 +178,43 @@ Coding Practice with Loops
}
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testForLoop() throws IOException
- {
- String target = "for (int x = 5;";
- boolean passed = checkCodeContains("for loop", target);
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop() throws IOException
+ {
+ String target = "for (int * = 5;";
+ boolean passed = checkCodeContains("for loop", target);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
+
Answer: In a ``for`` loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the ``for`` loop as shown below.
-
+
.. activecode:: ch6ex3a
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -222,69 +225,70 @@ Coding Practice with Loops
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex3d
-
+
.. tabbed:: ch6ex4
.. tab:: Question
-
+
.. activecode:: ch6ex4q
:language: java
:autograde: unittest
:practice: T
-
+
Rewrite the following code to use a ``while`` loop instead of a ``for`` loop to print out the numbers from 10 to 100 by 10's (inclusive).
~~~~
public class Test1
{
public static void main(String[] args)
{
- for (int x = 10; x <= 100; x=x+10)
- System.out.println(x);
+ for (int x = 10; x <= 100; x = x + 10) System.out.println(x);
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testForLoop() throws IOException
- {
- String target = "while (x";
- boolean passed = checkCodeContains("while loop", target);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop() throws IOException
+ {
+ String target = "while (";
+ boolean passed = checkCodeContains("while loop", target);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
-
+
+ Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
+
.. activecode:: ch6ex4a
:language: java
:optional:
-
- public class Test1
- {
+
+ public class Test1
+ {
public static void main(String[] args)
{
int x = 10;
@@ -295,23 +299,23 @@ Coding Practice with Loops
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex4d
-
-
+
+
.. tabbed:: ch6ex5
.. tab:: Question
-
+
.. activecode:: ch6ex5q
:language: java
:autograde: unittest
:practice: T
-
+
The following code should print the values from 1 to 10 (inclusive) but has errors. Fix the errors so that the code works as intended. If the code is in an infinite loop you can refresh the page in the browser to stop the loop and then click on Load History and move the bar above it to see your last changes.
~~~~
public class Test1
@@ -322,46 +326,49 @@ Coding Practice with Loops
while (x < 10)
{
System.out.println(x);
- }
- }
+ }
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
public void testMain() throws IOException
{
- String output = getMethodOutput("main");
- String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
+ String output = getMethodOutput("main");
+ String expect = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
}
@Test
- public void testWhileLoop() throws IOException
- {
- String target1 = "x = x + 1;";
- String target2 = "x++;";
- boolean passed1 = checkCodeContains("changing the loop variable variation 1", target1);
- boolean passed2 = checkCodeContains("changing the loop variable variation 2", target2);
- assertTrue(passed1 || passed2);
- }
- }
-
+ public void testWhileLoop() throws IOException
+ {
+ String target1 = "x=x+1;";
+ String target2 = "x++;";
+ String code = removeSpaces(getCode());
+ boolean passed = code.contains(target1) || code.contains(target2);
+ getResults("true", "" + passed, "changing the loop variable x");
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: On line 6 it should be ``while (x <= 10)``. Add line 9 at the end of the loop body to increment ``x`` so that the loop ends (isn't an infinite loop).
-
+
+ Answer: On line 6 it should be ``while (x <= 10)``. Add line 9 at the end of the loop body to increment ``x`` so that the loop ends (isn't an infinite loop).
+
.. activecode:: ch6ex5a
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -371,25 +378,25 @@ Coding Practice with Loops
{
System.out.println(x);
x++;
- }
- }
+ }
+ }
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex5d
-
+
.. tabbed:: ch6ex6
.. tab:: Question
-
+
.. activecode:: ch6ex6q
:language: java
:autograde: unittest
:practice: T
-
+
The following code should print the values from 10 to 5, but it has errors. Fix the errors so that the code works as intended.
~~~~
public class Test1
@@ -398,67 +405,66 @@ Coding Practice with Loops
{
for (int x = 10; x >= 5; x--)
{
- System.out.println(x);
- x--;
+ System.out.println(x);
+ x--;
}
-
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "10\n9\n8\n7\n6\n5\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "10\n9\n8\n7\n6\n5\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Remove the ``x--;`` at the end of the body of the loop. The change area in the for loop decrements ``x`` by 1, so this line isn't needed.
-
+
+ Answer: Remove the ``x--;`` at the end of the body of the loop. The change area in the for loop decrements ``x`` by 1, so this line isn't needed.
+
.. activecode:: ch6ex6a
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
for (int x = 10; x >= 5; x--)
{
- System.out.println(x);
+ System.out.println(x);
}
-
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex6d
-
+
.. tabbed:: ch6ex7n
.. tab:: Question
-
+
.. activecode:: ch6ex7nq
:language: java
:autograde: unittest
:practice: T
-
+
The following code should print the values from 10 to 1, but it has errors. Fix the errors so that the code works as intended.
~~~~
public class Test1
@@ -468,39 +474,40 @@ Coding Practice with Loops
int x = 10;
while (x >= 0)
{
- x--;
- System.out.println(x);
- }
+ x--;
+ System.out.println(x);
+ }
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
+
Answer: Move the ``x--;`` to the end of the loop body (after the ``System.out.println``. Change the ``while`` to ``x > 0``.
-
+
.. activecode:: ch6ex7na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -508,220 +515,229 @@ Coding Practice with Loops
int x = 10;
while (x > 0)
{
- System.out.println(x);
- x--;
+ System.out.println(x);
+ x--;
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex7nd
-
+
.. tabbed:: ch6ex8n
.. tab:: Question
-
+
.. activecode:: ch6ex8nq
:language: java
:autograde: unittest
:practice: T
-
+
Finish the code below to print a countdown from 100 to 0 by 10's using a for or while loop.
- ~~~~
+ ~~~~
public class Test1
{
- public static void main(String[] args)
- {
-
-
- }
+ public static void main(String[] args) {}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
public void testMain() throws IOException
{
- String output = getMethodOutput("main");
- String expect = "100\n90\n80\n70\n60\n50\n40\n30\n20\n10\n0\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testForLoop() throws IOException
- {
- String code = getCode();
- boolean passed = code.contains("for") || code.contains("while");
- getResults("Expected loop",""+passed, "Checking for loop",passed);
- assertTrue(passed);
- }
- }
+ String output = getMethodOutput("main");
+ String expect = "100\n90\n80\n70\n60\n50\n40\n30\n20\n10\n0\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop() throws IOException
+ {
+ String code = getCode();
+ boolean passed = code.contains("for") || code.contains("while");
+ getResults("Expected loop", "" + passed, "Checking for loop", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
+
Answer: You can use a ``for`` loop as shown below. Start ``x`` at 100, loop while it is greater or equal to 0, and subtract 10 each time after the body of the loop executes.
-
+
.. activecode:: ch6ex8na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
- for (int x = 100; x >= 0; x = x - 10)
- System.out.println(x);
+ for (int x = 100; x >= 0; x = x - 10) System.out.println(x);
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex8nd
-
-
+
+
.. tabbed:: ch6ex10n
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex10nq
:language: java
:autograde: unittest
- :practice: T
-
- Finish the code to print the value of ``x`` and ``" is even"`` if ``x`` is even and ``" is odd"`` if it is odd for all values from 10 to 1.
+ :practice: T
+
+ Finish the code to print the value of ``x`` and ``" is even"`` if ``x`` is even and ``" is odd"`` if it is odd for all values from 10 to 1.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
-
- }
+ public static void main(String[] args) {}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "10 is even\n9 is odd\n8 is even\n7 is odd\n6 is even\n5 is odd\n4 is even\n3 is odd\n2 is even\n1 is odd\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
-
- @Test
- public void testIfLoop()
- {
- String code = getCode();
- boolean passed = code.contains("if") && (code.contains("for") || code.contains("while"));
- getResults("Expected loop and if",""+passed, "Checking for loop and if statement",passed);
- assertTrue(passed);
- }
- }
-
-
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "10 is even\n"
+ + "9 is odd\n"
+ + "8 is even\n"
+ + "7 is odd\n"
+ + "6 is even\n"
+ + "5 is odd\n"
+ + "4 is even\n"
+ + "3 is odd\n"
+ + "2 is even\n"
+ + "1 is odd\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testIfLoop()
+ {
+ String code = getCode();
+ boolean passed = code.contains("if") && (code.contains("for") || code.contains("while"));
+ getResults(
+ "Expected loop and if", "" + passed, "Checking for loop and if statement", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use a ``for`` loop to loop from 10 to 1. Use a conditional to test if x is even (x % 2 == 0).
-
+
+ Answer: Use a ``for`` loop to loop from 10 to 1. Use a conditional to test if x is even (x % 2 == 0).
+
.. activecode:: ch6ex10na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
for (int x = 10; x >= 1; x--)
{
- if (x % 2 == 0)
+ if (x % 2 == 0)
+ {
System.out.println(x + " is even");
- else
+ }
+ else
+ {
System.out.println(x + " is odd");
+ }
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex10nd
-
+
.. tabbed:: ch6ex11n
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex11nq
:language: java
:autograde: unittest
:practice: T
-
+
Finish the code below to print the values for ``10 * x`` where ``x`` changes from 0 to 10 using a loop.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
-
- }
+ public static void main(String[] args) {}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "0\n10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void testForLoop()
- {
- // String target = "for (";
- // boolean passed = checkCodeContains("for loop", target);
- String code = getCode();
- boolean passed = code.contains("for") || code.contains("while");
- getResults("Expected loop",""+passed, "Checking for loop",passed);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "0\n10\n20\n30\n40\n50\n60\n70\n80\n90\n100\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ @Test
+ public void testForLoop()
+ {
+ // String target = "for (";
+ // boolean passed = checkCodeContains("for loop", target);
+ String code = getCode();
+ boolean passed = code.contains("for") || code.contains("while");
+ getResults("Expected loop", "" + passed, "Checking for loop", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
+
.. activecode:: ch6ex11na
:language: java
:optional:
-
- Answer: Use a ``for`` loop with ``x`` changing from 0 to 10 and print the value of ``x`` and ``10 * x``.
+
+ Answer: Use a ``for`` loop with ``x`` changing from 0 to 10 and print the value of ``x`` and ``10 * x``.
~~~~
public class Test1
{
@@ -729,12 +745,12 @@ Coding Practice with Loops
{
for (int x = 0; x <= 10; x++)
{
- System.out.println(x * 10);
+ System.out.println(x * 10);
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
@@ -743,57 +759,58 @@ Coding Practice with Loops
.. tabbed:: ch6ex9n
.. tab:: Question
-
+
.. activecode:: ch6ex9nq
:language: java
:autograde: unittest
:practice: T
-
- Finish the following code so that it prints a string message minus the last character each time through the loop until there are no more characters in message.
- ~~~~
+
+ Finish the following code so that it prints a string message minus the last character each time through the loop until there are no more characters in message.
+ ~~~~
public class Test1
{
public static void main(String[] args)
{
- String message = "help";
-
+ String message = "help";
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "help\nhel\nhe\nh\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void testForLoop()
- {
- String code = getCode();
- boolean passed = code.contains("for") || code.contains("while");
- getResults("Expected loop",""+passed, "Checking for loop",passed);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "help\nhel\nhe\nh\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ @Test
+ public void testForLoop()
+ {
+ String code = getCode();
+ boolean passed = code.contains("for") || code.contains("while");
+ getResults("Expected loop", "" + passed, "Checking for loop", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Add a ``while`` loop and loop while there is still at least one character in the string. At the end of the body of the loop reset the message to all characters except the last one.
-
+
+ Answer: Add a ``while`` loop and loop while there is still at least one character in the string. At the end of the body of the loop reset the message to all characters except the last one.
+
.. activecode:: ch6ex9na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -802,29 +819,28 @@ Coding Practice with Loops
while (message.length() > 0)
{
System.out.println(message);
- message = message.substring(0,message.length() - 1);
+ message = message.substring(0, message.length() - 1);
}
}
}
-
- .. tab:: Discussion
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex9nd
-
-
+
+
.. tabbed:: ch6ex12n
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex12nq
:language: java
:autograde: unittest
:practice: T
-
- Finish the code to loop printing the message each time through the loop and remove an ``x`` from the message until all the ``x``'s are gone.
+
+ Finish the code to loop printing the message each time through the loop and remove an ``x`` from the message until all the ``x``'s are gone.
~~~~
public class Test1
{
@@ -832,45 +848,54 @@ Coding Practice with Loops
{
String message = "Ix lovex youxxx";
System.out.println(message);
-
-
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
- //import java.util.regex.*;
- /* Do NOT change Main or CodeTestHelper.java. */
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Ix lovex youxxx\nI lovex youxxx\nI love youxxx\nI love youxx\nI love youx\nI love you\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void testForLoop()
- {
- String code = getCode();
- boolean passed = code.contains("for") || code.contains("while");
- getResults("Expected loop",""+passed, "Checking for loop",passed);
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ // import java.util.regex.*;
+ /* Do NOT change Main or CodeTestHelper.java. */
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "Ix lovex youxxx\n"
+ + "I lovex youxxx\n"
+ + "I love youxxx\n"
+ + "I love youxx\n"
+ + "I love youx\n"
+ + "I love you\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop()
+ {
+ String code = getCode();
+ boolean passed = code.contains("for") || code.contains("while");
+ getResults("Expected loop", "" + passed, "Checking for loop", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use a ``while`` loop. Loop while ``x`` has been found in the message (using ``indexOf``). Remove the ``x`` (using substring). Use indexOf again to get the position of the next ``x`` or -1 if there are none left in the message.
-
+
+ Answer: Use a ``while`` loop. Loop while ``x`` has been found in the message (using ``indexOf``). Remove the ``x`` (using substring). Use indexOf again to get the position of the next ``x`` or -1 if there are none left in the message.
+
.. activecode:: ch6ex12na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
@@ -880,29 +905,29 @@ Coding Practice with Loops
int pos = message.indexOf("x");
while (pos >= 0)
{
- message = message.substring(0,pos) + message.substring(pos+1);
- pos = message.indexOf("x");
- System.out.println(message);
+ message = message.substring(0, pos) + message.substring(pos + 1);
+ pos = message.indexOf("x");
+ System.out.println(message);
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex12nd
-
+
.. tabbed:: ch6ex16n
.. tab:: Question
-
+
.. activecode:: ch6ex16nq
:language: java
:autograde: unittest
:practice: T
-
+
Write a loop below to print the number of ``x``'s in the string message. Use the ``indexOf`` and ``substring`` methods.
~~~~
public class Test1
@@ -912,296 +937,305 @@ Coding Practice with Loops
String message = "xyxxzax";
}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "4";
-
- boolean passed = output.contains(expect);
- getResults(expect, output, "Expected output from main", passed);
- assertTrue(passed);
- }
- @Test
- public void testForLoop()
- {
- String code = getCode();
- boolean passed = code.contains("for") || code.contains("while");
- getResults("Expected loop",""+passed, "Checking for loop",passed);
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "4";
+
+ boolean passed = output.contains(expect);
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testForLoop()
+ {
+ String code = getCode();
+ boolean passed = code.contains("for") || code.contains("while");
+ getResults("Expected loop", "" + passed, "Checking for loop", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use indexOf to find the next ``x``. Loop while pos is greater than or equal to 0. Use substring to reset message beyond the next ``x``.
-
+
+ Answer: Use indexOf to find the next ``x``. Loop while pos is greater than or equal to 0. Use substring to reset message beyond the next ``x``.
+
.. activecode:: ch6ex16na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
-
+
String message = "xyxxzax";
int pos = message.indexOf("x");
int count = 0;
while (pos >= 0)
{
count++;
- message = message.substring(pos+1);
+ message = message.substring(pos + 1);
pos = message.indexOf("x");
}
System.out.println("There were " + count + " x's");
}
}
-
- .. tab:: Discussion
-
+
+ .. tab:: Discussion
+
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex16nd
-
+
.. tabbed:: ch6ex14n
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex14nq
:language: java
:autograde: unittest
:practice: T
-
+
Write the code below to print a rectangle of stars (``*``) with 5 rows of stars and 3 stars per row. Hint: use nested for loops.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- }
+ public static void main(String[] args) {}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "***\n***\n***\n***\n***\n";
-
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void test2() {
- String code = getCode();
- String target = "for (int * = #; * ? *; *~)";
-
- int num = countOccurencesRegex(code, target);
-
- boolean passed = num == 2;
-
- getResults("2", ""+num, "2 For loops (nested)", passed);
- assertTrue(passed);
- }
- }
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "***\n***\n***\n***\n***\n";
+
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "for (int * = #; * ? *; *~)";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num == 2;
+
+ getResults("2", "" + num, "2 For loops (nested)", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row.
-
+
+ Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row.
+
.. activecode:: ch6ex14na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
for (int row = 0; row < 5; row++)
{
- for (int col = 0; col < 3; col++)
- {
- System.out.print("*");
- }
- System.out.println();
+ for (int col = 0; col < 3; col++)
+ {
+ System.out.print("*");
+ }
+ System.out.println();
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex14nd
-
-
+
+
.. tabbed:: ch6ex15n
.. tab:: Question
-
+
.. activecode:: ch6ex15nq
:language: java
:autograde: unittest
:practice: T
-
- Write the code below to print a rectangle of stars (``*``) with 3 rows of stars and 5 stars per row.
+
+ Write the code below to print a rectangle of stars (``*``) with 3 rows of stars and 5 stars per row.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- }
+ public static void main(String[] args) {}
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "*****\n*****\n*****\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void test2() {
- String code = getCode();
- String target = "for (int * = #; * ? *; *~)";
+ import org.junit.*;
- int num = countOccurencesRegex(code, target);
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "*****\n*****\n*****\n";
- boolean passed = num == 2;
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
- getResults("2", ""+num, "2 For loops (nested)", passed);
- assertTrue(passed);
- }
- }
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "for (int * = #; * ? *; *~)";
+ int num = countOccurencesRegex(code, target);
+ boolean passed = num == 2;
+
+ getResults("2", "" + num, "2 For loops (nested)", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row.
-
+
+ Answer: Use nested ``for`` loops. Use the outer loop to control the number of rows and the inner loop to control the number of stars per row.
+
.. activecode:: ch6ex15na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
for (int row = 0; row < 3; row++)
{
- for (int col = 0; col < 5; col++)
- {
- System.out.print("*");
- }
- System.out.println();
+ for (int col = 0; col < 5; col++)
+ {
+ System.out.print("*");
+ }
+ System.out.println();
}
}
}
-
- .. tab:: Discussion
-
+
+ .. tab:: Discussion
+
.. disqus::
:shortname: cslearn4u
:identifier: javareview_ch6ex15nd
-
+
.. tabbed:: ch6ex13n
- .. tab:: Question
-
+ .. tab:: Question
+
.. activecode:: ch6ex13nq
:language: java
:autograde: unittest
:practice: T
-
- Write the code below to print 55555, 4444, 333, 22, 1 with each on a different line.
+
+ Write the code below to print 55555, 4444, 333, 22, 1 with each on a different line.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- }
- }
+ public static void main(String[] args) {}
+ }
+
====
import static org.junit.Assert.*;
- import org.junit.*;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "55555\n4444\n333\n22\n1\n";
- boolean passed = getResults(expect, output, "Expected output from main");
- assertTrue(passed);
- }
- @Test
- public void test2() {
- String code = getCode();
- String target = "for (int * = #; * ? *; *~)";
-
- int num = countOccurencesRegex(code, target);
-
- boolean passed = num == 2;
-
- getResults("2", ""+num, "2 For loops (nested)", passed);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "55555\n4444\n333\n22\n1\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "for (int * = #; * ? *; *~)";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num == 2;
+
+ getResults("2", "" + num, "2 For loops (nested)", passed);
+ assertTrue(passed);
+ }
+ }
.. tab:: Answer
-
- Answer: Use nested ``for`` loops. The outer loop controls what is printed on each row and the number of rows. The inner loop controls the number of values printer per row.
-
+
+ Answer: Use nested ``for`` loops. The outer loop controls what is printed on each row and the number of rows. The inner loop controls the number of values printer per row.
+
.. activecode:: ch6ex13na
:language: java
:optional:
-
+
public class Test1
{
public static void main(String[] args)
{
for (int x = 5; x >= 1; x--)
{
- for (int y = x; y > 0; y--)
- {
- System.out.print(x);
- }
- System.out.println();
+ for (int y = x; y > 0; y--)
+ {
+ System.out.print(x);
+ }
+ System.out.println();
}
}
}
-
- .. tab:: Discussion
+
+ .. tab:: Discussion
.. disqus::
:shortname: cslearn4u
- :identifier: javareview_ch6ex13nd
\ No newline at end of file
+ :identifier: javareview_ch6ex13nd
diff --git a/_sources/Unit5-Writing-Classes/APLine.rst b/_sources/Unit5-Writing-Classes/APLine.rst
index ca335b054..8af0c91ed 100644
--- a/_sources/Unit5-Writing-Classes/APLine.rst
+++ b/_sources/Unit5-Writing-Classes/APLine.rst
@@ -1,10 +1,8 @@
-
-
Free Response Question - APLine
================================
-.. index::
- single: apline
+.. index::
+ single: apline
single: free response
The following is a free response question from 2010. It was question 2 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
@@ -35,117 +33,123 @@ Try and Solve It
Write the `APLine` class. Your implementation must include a constructor that has three integer parameters that represent ``a``, ``b``, and ``c``, in that order.
You may assume that the values of the parameters representing ``a`` and ``b`` are not zero.
-It must also include a method ``getSlope`` that calculates and returns the slope of the line, and a method ``isOnLine`` that returns ``true`` if the point represented by its two parameters (``x`` and ``y``, in that order) is on the ``APLine`` and returns ``false`` otherwise.
-Your class must produce the indicated results when the main method below is run.
-You may ignore any issues related to integer overflow.
+
+It must also include a method ``getSlope()`` that calculates and returns the slope of the line (using the equation ``-a / b``) and a method ``isOnLine(x, y)`` that returns ``true`` if the point represented by its two parameters (``x`` and ``y``, in that order) is on the ``APLine`` and returns ``false`` otherwise, by testing if
+``ax + by + c`` is equal to 0.
+
+Your class must produce the indicated results when the main method below is run. You may ignore any issues related to integer overflow.
.. activecode:: APLineFRQ
:language: java
- :autograde: unittest
+ :autograde: unittest
+ Write a class APLine with instance variables, a constructor with 3 paramaters for a, b, c, and the methods getSlope() and isOnLine(x,y).
+ ~~~~
// Declare the APLine class
+
{
- /** State variables. Any numeric type; object or primitive. */
+ /** Declare instance variables */
/** Constructor with 3 int parameters. */
- /** Determine the slope of this APLine. */
+ /** method getSlope(): Determine the slope of this APLine. */
- /** Determine if coordinates represent a point on this APLine. */
+ /** method isOnLine(x,y): Determine if coordinates (x,y) represent a point on this APLine. */
/** Test with this main method */
- public static void main(String[] args)
+ public static void main(String[] args)
{
APLine line1 = new APLine(5, 4, -17);
double slope1 = line1.getSlope(); // slope1 is assigned -1.25
boolean onLine1 = line1.isOnLine(5, -2); // true because 5(5) + 4(-2) + (-17) = 0
-
+
APLine line2 = new APLine(-25, 40, 30);
double slope2 = line2.getSlope(); // slope2 is assigned 0.625
boolean onLine2 = line2.isOnLine(5, -2); // false because -25(5) + 40(-2) + 30 != 0
// Should print out true and false
System.out.println(onLine1 + " " + onLine2);
- }
+ }
}
====
// Test Code for Lesson 5.15 - FRQ - APLine
- import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import java.io.*;
+ import static org.junit.Assert.*;
+
+ import org.junit.Test;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("APLine");
+ // This sets default values for when objects are instantiated
+ Object[] values = new Object[] {3, 2, -6};
+ setDefaultValues(values);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = " true false";
+
+ boolean passed = getResults(expect, output, "Running main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testConstructor()
+ {
+ String output = checkConstructor(3);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking constructor with 3 parameters");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testGetSlope() throws IOException
+ {
+ double output = Double.parseDouble(getMethodOutput("getSlope"));
+ double expect = -1.5;
+
+ boolean passed = getResults(expect, output, "Checking method getSlope()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testIsOnLine1() throws IOException
+ {
+ Object[] args = {2, 0};
+ String output = getMethodOutput("isOnLine", args);
+ String expect = "true";
+
+ boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testIsOnLine2() throws IOException
+ {
+ Object[] args = {5, -2};
+ String output = getMethodOutput("isOnLine", args);
+ String expect = "false";
+
+ boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "3 Private";
+ // Will produce a printout with number of private and public variables
+ String output = testPrivateInstanceVariables();
+
+ boolean passed = getResults("3 Private", output, "Checking Instance Variable(s)");
+
+ assertTrue(passed);
+ }
+ }
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests()
- {
- super("APLine");
- // This sets default values for when objects are instantiated
- Object[] values = new Object[]{3, 2, -6};
- setDefaultValues(values);
- }
-
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = " true false";
-
- boolean passed = getResults(expect, output, "Running main");
- assertTrue(passed);
- }
-
- @Test
- public void testConstructor()
- {
- String output = checkConstructor(3);
- String expect = "pass";
-
- boolean passed = getResults(expect, output, "Checking constructor with 3 parameters");
- assertTrue(passed);
- }
-
- @Test
- public void testGetSlope() throws IOException
- {
- double output = Double.parseDouble(getMethodOutput("getSlope"));
- double expect = -1.5;
-
- boolean passed = getResults(expect, output, "Checking method getSlope()");
- assertTrue(passed);
- }
-
- @Test
- public void testIsOnLine1() throws IOException
- {
- Object[] args = {2, 0};
- String output = getMethodOutput("isOnLine", args);
- String expect = "true";
-
- boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)");
- assertTrue(passed);
- }
-
- @Test
- public void testIsOnLine2() throws IOException
- {
- Object[] args = {5, -2};
- String output = getMethodOutput("isOnLine", args);
- String expect = "false";
-
- boolean passed = getResults(expect, output, "Checking method isOnLine(5, -2)");
- assertTrue(passed);
- }
-
- @Test
- public void testPrivateVariables()
- {
- String expect = "3 Private";
- // Will produce a printout with number of private and public variables
- String output = testPrivateInstanceVariables();
-
- boolean passed = getResults("3 Private", output, "Checking Instance Variable(s)");
-
- assertTrue(passed);
- }
- }
diff --git a/_sources/Unit5-Writing-Classes/CBLabs.rst b/_sources/Unit5-Writing-Classes/CBLabs.rst
index af7777182..b45cbf866 100644
--- a/_sources/Unit5-Writing-Classes/CBLabs.rst
+++ b/_sources/Unit5-Writing-Classes/CBLabs.rst
@@ -4,11 +4,11 @@ College Board Celebrity and Data Labs
.. |Celebrity Lab| raw:: html
- Celebrity Lab
-
+ Celebrity Lab
+
.. |Data Lab| raw:: html
- Data Lab
-
-
-The new AP CS A Labs released in 2019, the |Celebrity Lab| (Activity 1-3) and the |Data Lab| (Activity 1 and 2 but not 3), are for students to practice writing classes. The teacher guide and the code files are available in the AP Course Audit Portal. This page will eventually include tips to complete the labs.
\ No newline at end of file
+ Data Lab
+
+
+The new AP CSA Labs released in 2019, the |Celebrity Lab| (Activity 1-2) and the |Data Lab| (Activity 1-2), are for students to practice writing classes. Each of these labs have further activities that you will finish after Unit 7. The teacher guide and the code files are available in the AP Course Audit Portal. This page will eventually include tips to complete the labs.
diff --git a/_sources/Unit5-Writing-Classes/Exercises.rst b/_sources/Unit5-Writing-Classes/Exercises.rst
index f30868bbd..41248ade6 100644
--- a/_sources/Unit5-Writing-Classes/Exercises.rst
+++ b/_sources/Unit5-Writing-Classes/Exercises.rst
@@ -1,63 +1,63 @@
.. qnum::
- :prefix: 5-12-
+ :prefix: 5-14-
:start: 1
-
-Exercises
-=========
+
+Multiple-Choice Exercises
+============================
.. mchoice:: AP5-1-3
:practice: T
The Liquid class will contain two double attributes for a liquid’s boiling point temperature and freezing point temperature. The class will also contain a constructor.
-
+
.. code-block:: java
public class Liquid
{
/* missing code */
}
- Which of the following replacements for /* missing code */ is the most appropriate
+ Which of the following replacements for /* missing code */ is the most appropriate
implementation of the class?
-
+
- .. code-block:: java
-
+
private double boilingPoint;
private double freezingPoint;
public Liquid(double boilingPoint, double freezingPoint)
{ /* implementation not shown */ }
+ Correct! The instance variables should be private and the constructor and methods should be public.
-
+
- .. code-block:: java
-
+
private double boilingPoint;
private double freezingPoint;
private Liquid(double boilingPoint, double freezingPoint)
{ /* implementation not shown */ }
- Constructors should be public.
-
+
- .. code-block:: java
-
+
private double boilingPoint;
public double freezingPoint;
private Liquid(double freezingPoint, double boilingPoint)
{ /* implementation not shown */ }
- The instance variables should be private and the constructor and methods should be public.
-
+
- .. code-block:: java
-
+
public double boilingPoint;
public double freezingPoint;
private Liquid(double boilingPoint, double freezingPoint)
{ /* implementation not shown */ }
- The instance variables should be private and the constructor and methods should be public.
-
+
- .. code-block:: java
-
+
public double freezingPoint;
public double boilingPoint;
public Liquid(double freezingPoint, double boilingPoint)
@@ -70,18 +70,18 @@ Exercises
:random:
The Cat class below will contain two String attributes and one int attribute for name, color, and age; a constructor; and an adoptCat method. The adoptCat method is intended to be accessed outside the class.
-
+
.. code-block:: java
public class Cat
{
/* missing code */
}
- Which of the following replacements for /* missing code */ is the most appropriate
+ Which of the following replacements for /* missing code */ is the most appropriate
implementation of the class?
-
+
- .. code-block:: java
-
+
private String name;
private String color;
private int age;
@@ -91,9 +91,9 @@ Exercises
{ /* implementation not shown */ }
- Method adoptCat() should be public.
-
+
- .. code-block:: java
-
+
public String name;
public String color;
public int age;
@@ -103,9 +103,9 @@ Exercises
{ /* implementation not shown */ }
- Method and constructor should be public, and instance variables should be private.
-
+
- .. code-block:: java
-
+
private String name;
private String color;
private int age;
@@ -115,9 +115,9 @@ Exercises
{ /* implementation not shown */ }
+ Correct! Method and constructor should be public, and instance variables should be private.
-
+
- .. code-block:: java
-
+
public String name;
public String color;
public int age;
@@ -127,9 +127,9 @@ Exercises
{ /* implementation not shown */ }
- Instance variables should be private.
-
+
- .. code-block:: java
-
+
public String name;
public String color;
public int age;
@@ -139,20 +139,20 @@ Exercises
{ /* implementation not shown */ }
- Instance variables should be private, and the constructor should be public.
-
+
.. mchoice:: AP5-2-4
:practice: T
:random:
Consider the definition of the Party class below. The class uses the instance variable numOfPeople to indicate how many people are at the party.
-
+
.. code-block:: java
public class Party
{
private int numOfPeople;
private String partyHost;
-
+
public Party (String name, int people)
{
partyHost = name;
@@ -162,23 +162,23 @@ Exercises
Which of the following statements will create a Party object
that represents a party that has three people at it?
-
+
- Party p = new Party ("Natasha", "3");
- An int should be passed in as the second parameter, not a String.
-
+
- Party p = new Party ("Eduardo", 3);
+ Correct
-
+
- Party p = new Party ("Emillio", "three");
- An int should be passed in as the second parameter, not a string.
-
+
- Party p = new Party ("Bob", three);
- The word three would be treated as an undeclared variable here.
-
+
- Party p = new Party ("Billie", "2+1");
- Strings cannot perform addition.
@@ -187,7 +187,7 @@ Exercises
:practice: T
:random:
:answer_a: I only
- :answer_b: I and II
+ :answer_b: I and II
:answer_c: I and III
:answer_d: I, II, and III
:answer_e: II and III
@@ -199,7 +199,7 @@ Exercises
:feedback_e: I can also create a correct Party instance
Consider the following class definition. Each object of the class Party will store the party host’s name as partyHost, the number of people as numOfPeople, and the capacity that the event can hold as capacity. Which of the following code segments, found in a class other than Party, can be used to create a party hosted by Charlie without anyone there initially, but the place can hold 78 people ?
-
+
.. code-block:: java
public class Party
@@ -232,7 +232,7 @@ Exercises
:random:
Consider the following class definition.
-
+
.. code-block:: java
public class Party
@@ -243,16 +243,16 @@ Exercises
}
The following statement appears in a method in a class other than Party. It is intended to create a new Party object p with its attributes set to 10 and 5.0.
-
+
.. code-block:: java
Party p = new Party(10, 5.0);
- Which of the following can be used to replace /* missing constructor */
+ Which of the following can be used to replace /* missing constructor */
so that the object p is correctly created?
-
+
- .. code-block:: java
-
+
public Party(int first, double second)
{
numOfPeople = 10;
@@ -262,7 +262,7 @@ Exercises
- The constructor should be using the local variables to set the instance variables.
- .. code-block:: java
-
+
public Party(int first, double second)
{
numOfPeople = first;
@@ -272,7 +272,7 @@ Exercises
+ Correct
- .. code-block:: java
-
+
public Party(int first, double second)
{
first = 10;
@@ -282,7 +282,7 @@ Exercises
- The constructor should be using the parameters to set the instance variables.
- .. code-block:: java
-
+
public Party(int first, double second)
{
first = numOfPeople;
@@ -290,7 +290,7 @@ Exercises
}
- The constructor should be changing the instance variables, not the local variables.
-
+
.. mchoice:: AP5-3-3
:practice: T
:random:
@@ -314,22 +314,22 @@ Exercises
/* Other methods not shown */
}
- Which of the following preconditions is reasonable for the Liquid constructor?
-
- - Precondition: fp \> 0
-
+ Which of the following preconditions is reasonable for the Liquid constructor?
+
+ - Precondition: fp \> 0
+
- Incorrect. The freezing point could be negative.
-
- - Precondition: currentTemp \> 0
-
+
+ - Precondition: currentTemp \> 0
+
- Incorrect. Unable to make this assumption for all liquids.
-
- - Precondition: fp < ct < bp
-
+
+ - Precondition: fp < ct < bp
+
+ Correct!
-
- - Precondition: fp > ct > bp
-
+
+ - Precondition: fp > ct > bp
+
- Incorrect. This would again result in freezing point being > boiling point which is impossible.
.. mchoice:: AP5-4-4
@@ -348,7 +348,7 @@ Exercises
:feedback_e: The accessor method getAge should return the instance variable age.
Consider the following Cat class, with the cat’s age stored in the method’s int attribute. The getAge method is intended to allow methods in other classes to access a Cat object’s age value; however, it does not work as intended. Which of the following best explains why the getAge method does NOT work as intended?
-
+
.. code-block:: java
public class Cat
@@ -366,13 +366,12 @@ Exercises
}
}
-
.. mchoice:: AP5-4-3
:practice: T
:random:
-
+
Consider the following Liquid class. The currentTemperature is stored in the method’s int attribute. The getCurrentTemp method is intended to allow methods in other classes to access a Liquid object’s currentTemperature value; however, it does not work as intended. Which of the following best explains why the getCurrentTemperature method does NOT work as intended?
-
+
.. code-block:: java
public class Liquid
@@ -391,32 +390,32 @@ Exercises
}
- The getCurrentTemperature method should be declared as private.
-
+
- Accessor methods should be public methods.
-
+
- The return type of the getCurrentTemperature method should be int.
-
+
+ Correct! The return type should match the type of the variable being returned.
- The getCurrentTemperature method should have at least one parameter.
-
+
- Get methods do not need parameters.
- The variable currentTemperature is not declared inside of the getCurrentTemperature method.
-
+
- currentTemperature is an instance variable that is shared by all the methods in the class.
- The instance variable ct should be returned instead of currentTemperature.
-
+
- The getCurrentTemperature method does not have access to the ct variable which is the parameter for the constructor.
-
+
.. mchoice:: AP5-5-3
:practice: T
:random:
Consider the following class definition.
-
+
.. code-block:: java
public class Liquid
@@ -430,9 +429,9 @@ Exercises
public int getTemp()
{
- return currentTemp;
+ return currentTemp;
}
-
+
public void resetTemp(int new_temp)
{
currentTemp = new_temp;
@@ -440,32 +439,32 @@ Exercises
}
Consider the following code segment, which appears in a method in a class other than Liquid. The code segment does not compile.
-
+
.. code-block:: java
Liquid liq = new Liquid(50);
System.out.println("The temperature of the liquid is " + liq.currentTemp);
Which of the following best identifies the reason the code segment does not compile?
-
+
- The Liquid class constructor should not have a parameter.
-
+
- The constructor does have a parameter.
-
+
- The resetTemperature method does not return a value that can be printed.
-
+
- This is a void mutator method.
-
+
- The private instance variable cannot be accessed from outside the class unless the accessor method is used.
-
+
+ Correct! The currentTemp instance variable is private and cannot be accessed outside of the class but the public accessor method getTemp() can be used instead.
-
+
- The getTemp method cannot be called from outside the Liquid class.
-
+
- The getTemp accessor method should be used from outside the class.
-
+
- currentTemp does not have a value.
-
+
- currentTemp is initialized to a value by the constructor but it is private and cannot be accessed outside the class.
@@ -474,7 +473,7 @@ Exercises
:random:
In the Liquid class below, the raiseTemperature method is intended to increase the value of the instance variable currentTemp by the value of the parameter increase. The method does not work as intended.
-
+
.. code-block:: java
public class Liquid
@@ -487,33 +486,33 @@ Exercises
}
public void raiseTemperature(int increase) // Line 10
- {
+ {
return currentTemp + increase; // Line 12
}
}
Which of the following changes should be made so that the class definition compiles without error and the method raiseTemperature works as intended?
-
+
- Replace line 12 with ``currentTemp += increase;``
-
+
+ Correct! This void mutator method should just change the value of currentTemp and not return a value.
-
+
- Replace line 12 with ``return currentTemp += increase;``
-
+
- This void mutator method should just change the value of currentTemp and not return a value.
-
+
- Replace line 12 with ``increase += currentTemp;``
-
+
- This method should change the value of currentTemp, not increase.
-
+
- Replace line 10 with ``public raiseTemperature(int increase)``
-
+
- This mutator method needs a return type of void.
-
+
- Replace line 10 with ``public int raiseTemperature(int increase)``
-
+
- This mutator method should have a void return value and just change the value of currentTemp without returning a value.
-
+
.. mchoice:: AP5-6-3
:practice: T
@@ -529,30 +528,28 @@ Exercises
:feedback_c: Assume you have 5 boxes at $10 each. You would need to multiply them to get a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person.
:feedback_d: Assume you have 5 boxes at $10 each for a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person.
:feedback_e: Assume you have 5 boxes at $10 each for a total cost of $50. If you had 10 people at the party, you would need to divide $50 by 10 to get $5 per person.
-
+
Consider the following class definition. The calculatePizzaCostPerPerson method is intended to calculate the amount each person at the party must pay for pizza. The amount is equal to the total price of all the pizza boxes divided by the number of people at the party. Which of the following code segments should replace *missing code* so that the calculatePizzaCostPerPerson method will work as intended?
-
+
.. code-block:: java
public class Party
{
- private int numOfPeople; //number of people at the party
+ private int numOfPeople; // number of people at the party
public Party(int people)
{
numOfPeople = people;
}
- public double calculatePizzaCostPerPerson(int numOfBoxes, double priceOfOnePizzaBox)
- {
+ public double calculatePizzaCostPerPerson(
+ int numOfBoxes, double priceOfOnePizzaBox)
+ {
/* missing code */
}
}
-
-
-
.. mchoice:: AP5-6-4
:practice: T
:random:
@@ -569,13 +566,13 @@ Exercises
:feedback_e: III would not work because you cannot put a shortcut assignment operator in the conditional test of an if statement.
Consider the Party class below.
-
+
.. code-block:: java
public class Party
{
- private int numOfPeople; //number of people at the party
- private int capacity; //total capacity of people at party
+ private int numOfPeople; // number of people at the party
+ private int capacity; // total capacity of people at party
public Party(int people, int cap)
{
@@ -588,11 +585,11 @@ Exercises
/* missing code */
}
}
-
+
The class contains the updateNumOfPeople method, which is intended to update the instance variable numOfPeople under certain conditions and return a value indicating whether the update was successful. If adding additionalPeople to the current number of people would lead to the number going over the capacity, then the update would be unsuccessful. Otherwise, if adding the number of additional people is still below or at the capacity, the update is successful. Which of the following code segments can replace *missing code* to ensure that the updateNumOfPeople method works as intended?
.. code-block:: java
-
+
I. if (numOfPeople + additionalPeople > capacity)
{
return false;
@@ -618,7 +615,7 @@ Exercises
else
{
return false;
- }
+ }
.. mchoice:: AP5-8-3
:practice: T
@@ -647,38 +644,37 @@ Exercises
{
currentTemp = newTemp + howMuch;
}
-
}
Which of the following best explains why the class will not compile?
-
+
- The class is missing an accessor method.
-
+
- The class does not necessarily need an accessor method.
-
+
- The instance variables currentTemp and boilingPoint should be public instead of private.
-
+
- Instance variables are usually private.
-
+
- The Liquid constructor needs a return type.
-
+
- Constructors do not have return types.
-
+
- The Liquid class is missing a constructor.
-
+
- The class includes a constructor.
-
+
- The variable newTemp is not defined in the increaseTemp method.
-
+
+ Correct! newTemp is defined in a different method. The instance variable currentTemp should be used instead.
-
+
.. mchoice:: AP5-8-4
:practice: T
:answer_a: The private variables boxesOfFood and numOfPeople are not properly initialized.
:answer_b: The private variables boxesOfFood and numOfPeople should have been declared public.
:answer_c: The public method getBoxesOfFood should have been declared private.
- :answer_d: The variable updatedAmountOfFood in the eatFoodBoxes method is not declared in this method.
+ :answer_d: The variable updatedAmountOfFood in the eatFood method is not declared in this method.
:answer_e: The variables boxesOfFood and numOfPeople in the updatedAmountOfFood method are local variables.
:correct: d
:feedback_a: The private variables boxesOfFood and numOfPeople are initialized by the constructor.
@@ -688,14 +684,14 @@ Exercises
:feedback_e: The variables boxesOfFood and numOfPeople are instance variables.
Consider the following class definition for Party. The following code segment appears in a method in a class other than Party. The code segment is intended to print the value 30, but does not print the correct value because of an error in the Party class. Which of the following best explains why the correct value isn’t printed?
-
+
.. code-block:: java
-
+
Party p = new Party(20, 15);
p.orderMoreFood(20);
p.eatFood(5);
System.out.println(p.getBoxesOfFood());
-
+
public class Party
{
private int boxesOfFood;
@@ -721,18 +717,18 @@ Exercises
return boxesOfFood;
}
- public void eatFood(int eatenBoxes)
+ public void eatFood(int eatenBoxes)
{
boxesOfFood = updatedAmountOfFood - eatenBoxes;
}
}
-
+
.. mchoice:: AP5-9-3
:practice: T
- Consider the following class definitions.
-
+ Consider the following class definitions.
+
.. code-block:: java
public class Party
@@ -741,7 +737,7 @@ Exercises
private int monthOfParty;
private int partyStartTime;
- public Party (String h, int month, int startTime)
+ public Party(String h, int month, int startTime)
{
partyHost = h;
monthOfParty = month;
@@ -792,11 +788,10 @@ Exercises
}
}
-
Consider the following code segment, which appears in a class other than Party or PartyOptions.
-
+
.. code-block:: java
-
+
Party p1 = new Party("Kerry", 10, 7);
Party p2 = new Party("Jules", 9, 6);
@@ -805,20 +800,20 @@ Exercises
p2.addToOptions(options);
- Party by Kerry rejected; Party by Jules rejected;
-
+
- Kerry's party should be accepted because it is in the 10th month.
-
+
- Party by Kerry rejected; Party by Jules accepted;
-
- - Kerry's party should be accepted because it is in the 10th month. Jules' party should be rejected because it is not in the 10th month.
-
+
+ - Kerry's party should be accepted because it is in the 10th month. Jules' party should be rejected because it is not in the 10th month.
+
- Party by Kerry accepted; Party by Jules rejected;
-
+
+ Kerry's party is accepted because it is in the 10th month, and Jules' party is not.
-
+
- Party by Kerry accepted; Party by Jules accepted;
-
- - Jules' party should be rejected because it is not in the 10th month.
+
+ - Jules' party should be rejected because it is not in the 10th month.
diff --git a/_sources/Unit5-Writing-Classes/FRQstepTracker.rst b/_sources/Unit5-Writing-Classes/FRQstepTracker.rst
index 100b779d6..15eaaa559 100644
--- a/_sources/Unit5-Writing-Classes/FRQstepTracker.rst
+++ b/_sources/Unit5-Writing-Classes/FRQstepTracker.rst
@@ -1,34 +1,20 @@
+.. include:: ../common.rst
+
.. qnum::
- :prefix: 5-13-
+ :prefix: 5-16-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
Free Response Question (FRQ) for Classes
-----------------------------------------------------
-.. index::
+.. index::
single: class
single: free response
As of 2019, the AP exam's second free response question (FRQ) is on classes, where students design and implement a described class. This question involves creating a class with private instance variables and public methods. The College Board will provide a description of the class and the methods. This question does not involve more complex topics such as arrays.
-To succeed on the FRQ Question 2 on Classes, you must know how to:
+To succeed on the FRQ Question 2 on Classes, you must know how to:
- Create a class using ``public class Classname { }``
@@ -88,10 +74,10 @@ The following table contains a sample code execution sequence and the correspond
- - + + This question asks you to write the complete StepTracker class, including the constructor and any required instance variables and -methods. Your implementation must meet all specifications and conform to the example. +methods. Your implementation must meet all specifications and conform to the example. |Groupwork| Determining the Instance Variables ============================================== @@ -100,93 +86,154 @@ Work in pairs or groups to read through the problem statement and determine the It may help to first identify the variables that are needed for the constructor and the accessor and mutator methods. +.. clickablearea:: steptracker_instance_variables + :question: Select the phrases below which probably mention an instance variable. Note that some of these may be referring to the same variable or to local variables. + :feedback: Think about phrases that indicate a value that is being stored or changed or returned. + :iscode: + + This question involves the implementation of :click-incorrect:a fitness tracking system:endclick: + that is represented by the :click-incorrect:**StepTracker** class.:endclick: + + :click-incorrect:A StepTracker object:endclick: is created with a parameter that defines + :click-correct:the minimum number of steps that must be taken for a day to be active.:endclick: + + :click-incorrect:The StepTracker class:endclick: provides a constructor and the following methods. + + - addDailySteps, which accumulates :click-correct:information about steps:endclick: in readings + taken once per day. + + - activeDays, which returns :click-correct:the number of active days.:endclick: + + - averageSteps, which returns :click-correct:the average number of steps per day:endclick: + calculated by dividing :click-correct:the total number of steps taken:endclick: + by :click-correct:the number of days tracked.:endclick: + +Click to reveal multiple choice questions that will help you to determine the instance variables through the constructor parameters and accessor and mutator methods. + +.. reveal:: steptraker_ctor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-constructor + :answer_a: the minimum number of steps that must be taken for a day to be considered active + :answer_b: the number of active days + :answer_c: the average number of steps per day + :answer_d: the total number of steps taken + :answer_e: number of days tracked + :correct: a + :feedback_a: Yes, the problem definition describes this as a parameter to create a StepTracker object. + :feedback_b: This is not described as a parameter to create an StepTracker object. + :feedback_c: This is not described as a parameter to create an StepTracker object. + :feedback_d: This is not described as a parameter to create an StepTracker object. + :feedback_e: This is not described as a parameter to create an StepTracker object. + + Given the StepTracker class description above, which of these statements describes an instance variable that the StepTracker constructor should set using a parameter? + +.. reveal:: accessor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor + :answer_a: StepTracker tr = new StepTracker(1000) + :answer_b: tr.addDailysteps(1000); + :answer_c: tr.activeDays(); + :correct: c + :feedback_a: This is a call to the constructor. + :feedback_b: No, addDailySteps(1000) probably adds the given steps to an instance variable as a mutator method. + :feedback_c: Yes, activeDays() is an accessor method that returns the number of active days (a great instance variable!). + + Which of the following methods is an accessor method that returns the value of an instance variable? + +.. reveal:: mutator_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator + :answer_a: StepTracker tr = new StepTracker(1000) + :answer_b: tr.addDailysteps(1000); + :answer_c: tr.activeDays(); + :answer_d: tr.averageSteps(); + :correct: b + :feedback_a: No, this is a call to the constructor. + :feedback_b: Yes, addDailySteps(1000) is a mutator method that adds the steps given as a parameter to an instance variable that keeps track of the steps taken so far. + :feedback_c: No, activeDays() is an accessor method that returns the number of active days. + :feedback_d: No, averageSteps() is a complex accessor method that calculates and returns the average number of steps from the instance variable. + + Which of the following methods is a mutator method that changes the value of an instance variable? -.. clickablearea:: steptracker_instance_variables - :question: Select the phrases below which probably mention an instance variable. Note that some of these may be referring to the same variable or to local variables. - :feedback: Think about phrases that indicate a value that is being stored or changed or returned. - :iscode: - - This question involves the implementation of :click-incorrect:a fitness tracking system that is represented by the **StepTracker** class.:endclick: - - :click-incorrect:A StepTracker object:endclick: is created with a parameter that defines :click-correct:the minimum number of steps that must be taken for a day to be considered active. :endclick: - - :click-incorrect:The StepTracker class:endclick: provides a constructor and the following methods. - - - addDailySteps, which accumulates :click-correct:information about steps:endclick:, in readings taken once per day. - - - activeDays, which returns :click-correct:the number of active days.:endclick: - - - averageSteps, which returns :click-correct:the average number of steps per day:endclick:, calculated by dividing :click-correct:the total number of steps taken:endclick: by :click-correct:the number of days tracked.:endclick: - -.. mchoice:: steptracker-constructor - :answer_a: the minimum number of steps that must be taken for a day to be considered active - :answer_b: the number of active days - :answer_c: the average number of steps per day - :answer_d: the total number of steps taken - :answer_e: number of days tracked - :correct: a - :feedback_a: Yes, the problem definition describes this as a parameter to create a StepTracker object. - :feedback_b: This is not described as a parameter to create an StepTracker object. - :feedback_c: This is not described as a parameter to create an StepTracker object. - :feedback_d: This is not described as a parameter to create an StepTracker object. - :feedback_e: This is not described as a parameter to create an StepTracker object. - - Given the StepTracker class description above, which of these statements describes an instance variable that the StepTracker constructor should set using a parameter? - -.. mchoice:: steptracker-accessor - :answer_a: StepTracker tr = new StepTracker(1000) - :answer_b: tr.addDailysteps(1000); - :answer_c: tr.activeDays(); - :correct: c - :feedback_a: This is a call to the constructor. - :feedback_b: No, addDailySteps(1000) probably adds the given steps to an instance variable as a mutator method. - :feedback_c: Yes, activeDays() is an accessor method that returns the number of active days (a great instance variable!). - - Which of the following methods is an accessor method that returns the value of an instance variable? - -.. mchoice:: steptracker-mutator - :answer_a: StepTracker tr = new StepTracker(1000) - :answer_b: tr.addDailysteps(1000); - :answer_c: tr.activeDays(); - :answer_d: tr.averageSteps(); - :correct: b - :feedback_a: No, this is a call to the constructor. - :feedback_b: Yes, addDailySteps(1000) is a mutator method that adds the steps given as a parameter to an instance variable that keeps track of the steps taken so far. - :feedback_c: No, activeDays() is an accessor method that returns the number of active days. - :feedback_d: No, averageSteps() is a complex accessor method that calculates and returns the average number of steps from the instance variable. - - Which of the following methods is a mutator method that changes the value of an instance variable? - .. shortanswer:: steptracker-variables - What are the instance variables (at least 4!) that you need for the StepTracker class? What are the data types for each instance variable? - + What are the instance variables (at least 4!) that you need for the StepTracker class? What are the data types for each instance variable? + Writing the Class Header and Constructor ======================================== -You will receive at least 1 point if you write the class header and a constructor that has the same name as the class and no return type. You will receive another point for creating **private** instance variables inside the class. Complete the class definition below with the class name, the instance variables you determined above, and the constructor. Remember that for this problem, a StepTracker object is created (with a constructor) with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. The constructor will often have a parameter which it should assign to an instance variable. It should also assign default values to the other instance variables. +You will receive at least 1 point if you write the class header and a constructor that has the same name as the class and no return type. You will receive another point for creating **private** instance variables inside the class. Complete the class definition below with the class name, the instance variables you determined above, and the constructor. Remember that for this problem, a StepTracker object is created (with a constructor) with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. The constructor will often have a parameter which it should assign to an instance variable. It should also assign default values to the other instance variables. .. activecode:: stepTrackerCode1 :language: java + :autograde: unittest Write the first draft of the class StepTracker below with the class name, the instance variables, and the constructor with a parameter for the minimum number of steps threshold for active days. Make sure it compiles. ~~~~ - // Write class name here - + // Write public class your classname here and delete comment { // write instance variable declarations here - - + + // write the constructor with a parameter here - - + + public static void main(String[] args) { StepTracker tr = new StepTracker(10000); } } - + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + // Tests for ActiveCode StepTrackerCode1 + public class RunestoneTests extends CodeTestHelper + { + @Test + public void test1() + { + // check class name + boolean passed = checkCodeContains("correct class heading", "public class StepTracker"); + assertTrue(passed); + } + + @Test + public void test2() + { + // constructor with 1 parameter for threshold minSteps + String args = "int"; + String results = checkConstructor(args); + + boolean passed = getResults("pass", results, "Checking constructor with one int argument"); + assertTrue(passed); + } + + @Test + public void test3() + { + // check int - declaration of instance variables and parameter in constructor + String actual = testPrivateInstanceVariables(); + String expected = "4 Private"; + + boolean passed = getResults(expected, actual, "Checking declaration of instance variables"); + assertTrue(passed); + } + } + Here is the rubric for the instance variables and the constructor for this problem. Did you receive all 3 points? In class, your teacher may have you grade each others' code. @@ -201,7 +248,7 @@ Here is the rubric for the instance variables and the constructor for this probl Writing the Accessor Method activeDays ======================================== -Each method in the FRQ is worth 1 - 3 points. The method header is usually worth 1 point and the code in the method body is usually worth another point or two depending on how complex it is. +Each method in the FRQ is worth 1 - 3 points. The method header is usually worth 1 point and the code in the method body is usually worth another point or two depending on how complex it is. This problem asks you to write a simple accessor method called **activeDays** which returns the number of active days (which should be an instance variable) for 1 point. @@ -209,59 +256,101 @@ Remember that accessor methods usually look like the following: .. code-block:: java - class ExampleClass - { - //Instance variable declaration - private typeOfVar varName; - - // Accessor method template - public typeOfVar getVarName() - { - return varName; - } + class ExampleClass + { + // Instance variable declaration + private typeOfVar varName; + + // Accessor method template + public typeOfVar getVarName() + { + return varName; + } } - -.. mchoice:: steptracker-accessor-header - :practice: T - :answer_a: public void activeDays() - :answer_b: private void activeDays() - :answer_c: public int activeDays(int numSteps) - :answer_d: public void activeDays(int numSteps) - :answer_e: public int activeDays() - :correct: e - :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. - :feedback_b: Accessor methods should not be private. - :feedback_c: Accessor methods do not usually take parameters. - :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. - :feedback_e: Correct, accessor methods are public, have a return type, and no parameter. - - Which of the following is a good method header for the accessor method activeDays()? + +Click to reveal a multiple choice problem to help you determine the accessor method header. + +.. reveal:: steptracker_accessor_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor-header + :answer_a: public void activeDays() + :answer_b: private void activeDays() + :answer_c: public int activeDays(int numSteps) + :answer_d: public void activeDays(int numSteps) + :answer_e: public int activeDays() + :correct: e + :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. + :feedback_b: Accessor methods should not be private. + :feedback_c: Accessor methods do not usually take parameters. + :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. + :feedback_e: Correct, accessor methods are public, have a return type, and no parameter. + + Which of the following is a good method header for the accessor method activeDays()? .. activecode:: stepTrackerCode2 :language: java + :autograde: unittest Copy the code from your first draft of the class StepTracker above with the instance variables and constructor. Write the accessor methods **activeDays** which returns the number of active days. ~~~~ public class StepTracker { - // copy the instance variable declarations here - - - // copy the constructor with a parameter here - - // Write the accessor method activeDays() here - // @return activeDays - - public static void main(String[] args) - { - StepTracker tr = new StepTracker(10000); - System.out.println(tr.activeDays()); // returns 0. No data have been recorded yet. - } + // copy the instance variable declarations here + + // copy the constructor with a parameter here + + // Write the accessor method activeDays() here + // @return activeDays + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + System.out.println( + tr.activeDays()); // returns 0. No data have been recorded yet. + } } - -Here is the rubric for the accessor method activeDays() for this problem. The second column is small mistakes that will still earn the point but the third column is larger mistakes that will not earn the point. Did you receive the point for this method? In class, your teacher may have you grade each others' code. - + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check accessor method activeDays() + boolean passed = checkCodeContains("activeDays() method", "public int activeDays()"); + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check that activeDays() returns a value + boolean passed = checkCodeContains("return"); + assertTrue(passed); + } + } + +Here is the rubric for the accessor method ``activeDays`` for this problem. The second column is small mistakes that will still earn the point but the third column is larger mistakes that will not earn the point. Did you receive the point for this method? In class, your teacher may have you grade each others' code. + + .. figure:: Figures/stepTrackerRubric3.png :width: 700px :align: center @@ -269,48 +358,54 @@ Here is the rubric for the accessor method activeDays() for this problem. The se :figclass: align-center Figure 2: Rubric for accessor method activeDays() - + Writing the Mutator Method addDailySteps ======================================== -This problem asks you to write a more complex mutator method called addDailySteps worth 3 points. +This problem asks you to write a more complex mutator method called addDailySteps worth 3 points. Remember that mutator methods often look like the following: .. code-block:: java - - class Example + + class Example { - //Instance variable declaration + // Instance variable declaration private typeOfVar varName; // Mutator method template public void changeVarName(typeOfVar newValue) { - // an instance variable is changed through = or an operator like +=, -=, ++, etc. - varName = newValue; + // an instance variable is changed through = or an operator like +=, -=, + // ++, etc. + varName = newValue; } } - - -.. mchoice:: steptracker-mutator-header - :practice: T - :answer_a: public void addDailySteps() - :answer_b: private void addDailySteps() - :answer_c: public int addDailySteps(int numSteps) - :answer_d: public void addDailySteps(int numSteps) - :answer_e: private int addDailySteps() - :correct: d - :feedback_a: Mutator methods take a parameter to change the value of an instance variable. - :feedback_b: Mutator methods should not be private. - :feedback_c: Mutator methods do not usually return a value. - :feedback_d: Correct, mutator methods are public with a void return type and take a parameter to change the value of an instance variable. - :feedback_e: Mutator methods should not be private and should take a parameter to change the value of an instance variable. - - Which of the following is a good method header for the mutator method addDailySteps? - + +Click to reveal a multiple choice problem to help you determine the mutator method header. + +.. reveal:: steptracker_mutator_r1 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator-header + :answer_a: public void addDailySteps() + :answer_b: private void addDailySteps() + :answer_c: public int addDailySteps(int numSteps) + :answer_d: public void addDailySteps(int numSteps) + :answer_e: private int addDailySteps() + :correct: d + :feedback_a: Mutator methods take a parameter to change the value of an instance variable. + :feedback_b: Mutator methods should not be private. + :feedback_c: Mutator methods do not usually return a value. + :feedback_d: Correct, mutator methods are public with a void return type and take a parameter to change the value of an instance variable. + :feedback_e: Mutator methods should not be private and should take a parameter to change the value of an instance variable. + + Which of the following is a good method header for the mutator method addDailySteps? + The code for this mutator method is a little more complex than the template above, because it needs to change more than 1 instance variable. Notice the comments in the sample code execution: .. raw:: html @@ -329,52 +424,105 @@ The code for this mutator method is a little more complex than the template abov
-Consider each of your instance variables and whether this method should change them. - -.. mchoice:: steptracker-mutator-changes - :answer_a: the minimum number of steps that must be taken for a day to be considered active - :answer_b: the number of active days - :answer_c: the average number of steps per day - :answer_d: the total number of steps taken - :answer_e: number of days tracked - :correct: b, d, e - :feedback_a: The minimum is set by the constructor. - :feedback_b: Yes, addDailySteps should determine whether the number of steps given in its parameter is an active day and if so, change this variable. - :feedback_c: This method does not have to calculate the average. - :feedback_d: Yes, addDailySteps should add the number of steps taken that day in its parameter to the total. - :feedback_e: Yes, addDailySteps is called each day and can change the variable for the number of days being tracked. - - Which of the following values does the mutator method addDailySteps need to change? (check all that apply) - +Consider each of your instance variables and whether this method should change them. The problem which you can reveal below may help you. + +.. reveal:: steptracker_mutator_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-mutator-changes + :answer_a: the minimum number of steps that must be taken for a day to be considered active + :answer_b: the number of active days + :answer_c: the average number of steps per day + :answer_d: the total number of steps taken + :answer_e: number of days tracked + :correct: b, d, e + :feedback_a: The minimum is set by the constructor. + :feedback_b: Yes, addDailySteps should determine whether the number of steps given in its parameter is an active day and if so, change this variable. + :feedback_c: This method does not have to calculate the average. + :feedback_d: Yes, addDailySteps should add the number of steps taken that day in its parameter to the total. + :feedback_e: Yes, addDailySteps is called each day and can change the variable for the number of days being tracked. + + Which of the following values does the mutator method addDailySteps need to change? (check all that apply) + .. activecode:: stepTrackerCode3 :language: java + :autograde: unittest Copy the code from your draft of the class StepTracker above with the class name, the instance variables, constructor, and accessory method. Write the mutator method **addDailySteps** which takes a parameter and adds it to the appropriate instance variable and changes other instance variables appropriately. ~~~~ public class StepTracker { - // copy the instance variable declarations here - - - // copy the constructor with a parameter here - - // copy the accessor method activeDays() here. - - // Write the mutator method addDailySteps here. - // @param number of steps taken that day - - - - public static void main(String[] args) - { - StepTracker tr = new StepTracker(10000); - System.out.println(tr.activeDays()); // returns 0. No data have been recorded yet. - tr.addDailySteps(9000); // This is too few steps for the day to be considered active. - tr.addDailySteps(5000); // This is too few steps for the day to be considered active. - System.out.println(tr.activeDays()); // returns 0. No day had at least 10,000 steps. - tr.addDailySteps(13000); // This represents an active day. - System.out.println(tr.activeDays()); // returns 1. Of the three days for which step data were entered, one day had at least 10,000 steps. - } + // copy the instance variable declarations here + + // copy the constructor with a parameter here + + // copy the accessor method activeDays() here. + + // Write the mutator method addDailySteps here. + // @param number of steps taken that day + + public static void main(String[] args) + { + StepTracker tr = new StepTracker(10000); + + // returns 0. No data have been recorded yet. + System.out.println(tr.activeDays()); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(9000); + + // This is too few steps for the day to be considered active. + tr.addDailySteps(5000); + + // returns 0. No day had at least 10,000 steps. + System.out.println(tr.activeDays()); + + // This represents an active day. + tr.addDailySteps(13000); + + // returns 1. Of the three days for which step data were entered, one day + // had at least 10,000 steps. + System.out.println(tr.activeDays()); + } + } + + ==== + import static org.junit.Assert.*; + + import org.junit.*; + + import java.io.*; + + public class RunestoneTests extends CodeTestHelper + { + @Test + public void testMain() throws IOException + { + String output = getMethodOutput("main"); + String expect = "0\n0\n1\n"; + boolean passed = getResults(expect, output, "Expected output from main"); + assertTrue(passed); + } + + @Test + public void checkCodeContains1() + { + // check mutator method addDailySteps() + boolean passed = + checkCodeContains( + "addDailySteps method with parameter", "public void addDailySteps(int"); + assertTrue(passed); + } + + @Test + public void checkCodeContains2() + { + // check mutator method addDailySteps() contains "if" + boolean passed = checkCodeContains("if statement", "if ("); + assertTrue(passed); + } } Here is the rubric for the mutator method for this problem. The second column is small mistakes that will still earn the point but the third column is larger mistakes that will not earn the point. Did you receive all the points? In class, your teacher may have you grade each others' code. @@ -386,85 +534,161 @@ Here is the rubric for the mutator method for this problem. The second column is :figclass: align-center Figure 3: Rubric for mutator method - + Writing the Accessor Method averageSteps ========================================== -This problem asks you to write a more complex accessor method which uses the instance variables to calculate and return the **averageSteps** for 2 points. This method returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked. - - -.. mchoice:: steptracker-accessor-header2 - :practice: T - :answer_a: public void averageSteps() - :answer_b: public int averageSteps() - :answer_c: public double averageSteps() - :answer_d: public void averageSteps(int numSteps) - :answer_e: public int averageSteps(int numSteps) - :correct: c - :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. - :feedback_b: When you compute an average using division, you usually end up with a double value, not int. - :feedback_c: Correct, accessor methods are public, have a return type, and no parameter. In this case, returning an average requires a double return type. - :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. - :feedback_e: Accessor methods do not usually take parameters. - - Which of the following is a good method header for the accessor method averageSteps() which returns the average number of steps per day? - +This problem asks you to write a more complex accessor method which uses the instance variables to calculate and return the **averageSteps** for 2 points. This method returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked. + +Click to reveal a multiple choice problem to help you determine the accessor method header. + +.. reveal:: steptracker_accessor_r2 + :showtitle: Reveal Problem + :hidetitle: Hide Problem + :optional: + + .. mchoice:: steptracker-accessor-header2 + :answer_a: public void averageSteps() + :answer_b: public int averageSteps() + :answer_c: public double averageSteps() + :answer_d: public void averageSteps(int numSteps) + :answer_e: public int averageSteps(int numSteps) + :correct: c + :feedback_a: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables. + :feedback_b: When you compute an average using division, you usually end up with a double value, not int. + :feedback_c: Correct, accessor methods are public, have a return type, and no parameter. In this case, returning an average requires a double return type. + :feedback_d: Accessor methods need a return type since they return the value of an instance variable or a value calculated from instance variables, and they do not usually have a parameter. + :feedback_e: Accessor methods do not usually take parameters. + + Which of the following is a good method header for the accessor method averageSteps() which returns the average number of steps per day? + The complex accessor method **averageSteps()** must calculate the average number of steps from your instance variables. Notice that the first time it is called in the sample code execution, it returns 0.0 since there are no steps recorded. This avoids a divide by 0 error. .. raw:: html -
| Statements and Expressions | Value Returned (blank if no value) | Comment |
|---|
| Statements and Expressions | Value Returned (blank if no value) | Comment |
|---|---|---|
| tr.averageSteps(); | 0.0 | When no step data have been recorded, the averageSteps method returns 0.0. |
-
+
.. activecode:: stepTrackerCode4
:language: java
+ :autograde: unittest
Copy the code from your draft of the class StepTracker above with the instance variables, constructor, accessor and mutator methods. Write the accessor method **averageSteps** which returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked.
~~~~
public class StepTracker
{
- // copy the instance variable declarations here
-
-
- // copy the constructor with a parameter here
-
- // copy the accessor method activeDays() here
-
-
- // copy the mutator method addDailySteps here.
- // @param number of steps taken that day
-
-
- //Write the accessor method averageSteps() here
- // @return average steps calculated by dividing the total number of steps taken by the number of days tracked (which should be instance variables).
-
-
-
-
- public static void main(String[] args)
- {
- StepTracker tr = new StepTracker(10000);
- System.out.println(tr.activeDays()); // returns 0. No data have been recorded yet.
- System.out.println(tr.averageSteps()); // returns 0.0. When no step data have been recorded, the averageSteps method returns 0.0.
- tr.addDailySteps(9000); // This is too few steps for the day to be considered active.
- tr.addDailySteps(5000); // This is too few steps for the day to be considered active.
- System.out.println(tr.activeDays()); // returns 0. No day had at least 10,000 steps.
- System.out.println(tr.averageSteps()); // returns 7000.0 The average number of steps per day is (14000 / 2).
- tr.addDailySteps(13000); // This represents an active day.
- System.out.println(tr.activeDays()); // returns 1. Of the three days for which step data were entered, one day had at least 10,000 steps.
- System.out.println(tr.averageSteps()); // returns 9000.0. The average number of steps per day is (27000 / 3).
- tr.addDailySteps(23000); // This represents an active day.
- tr.addDailySteps(1111); // This is too few steps for the day to be considered active.
- System.out.println(tr.activeDays()); // returns 2. Of the five days for which step data were entered, two days had at least 10,000 steps.
- System.out.println(tr.averageSteps()); // returns 10222.2. The average number of steps per day is (51111 / 5).
- }
+ // copy the instance variable declarations here
+
+ // copy the constructor with a parameter here
+
+ // copy the accessor method activeDays() here.
+
+ // Write the mutator method addDailySteps here.
+ // @param number of steps taken that day
+
+ public static void main(String[] args)
+ {
+ StepTracker tr = new StepTracker(10000);
+ // returns 0. No data has been recorded yet.
+ System.out.println(tr.activeDays());
+ // returns 0.0. When no step data have been recorded,
+ // the averageSteps method returns 0.0
+ System.out.println(tr.averageSteps());
+
+ // This is too few steps for the day to be considered active.
+ tr.addDailySteps(9000);
+
+ // This is too few steps for the day to be considered active.
+ tr.addDailySteps(5000);
+
+ // returns 0. No day had at least 10,000 steps.
+ System.out.println(tr.activeDays());
+ // returns 7000.0 The average number of steps per day is (14000/2).
+ System.out.println(tr.averageSteps());
+
+ // This represents an active day.
+ tr.addDailySteps(13000);
+ // returns 1. Of the three days for which step data were entered,
+ // one day had at least 10,000 steps.
+ System.out.println(tr.activeDays());
+ // returns 9000.0. The average number of steps per day is (27000/3).
+ System.out.println(tr.averageSteps());
+
+ tr.addDailySteps(23000); // This represents an active day.
+ tr.addDailySteps(1111); // This is too few steps for the day to be active.
+ // returns 2. Of the five days for which step data were entered,
+ // two days had at least 10,000 steps.
+ System.out.println(tr.activeDays());
+ // returns 10222.2. The average number of steps per day is (51111/5).
+ System.out.println(tr.averageSteps());
+ }
}
-
-Here is the rubric for the averageSteps method for this problem. Did you receive all the points? In class, your teacher may have you grade each others' code.
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "0\n0.0\n0\n7000.0\n1\n9000.0\n2\n10222.2\n";
+ boolean passed =
+ getResults(
+ expect,
+ output,
+ "Expected output from main. Make sure you used casting to double for the"
+ + " last result!");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeContains1()
+ {
+ // check mutator method averageSteps()
+ boolean passed = checkCodeContains("averageSteps() method", "public double averageSteps()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeZero()
+ {
+ StepTracker tr = new StepTracker(10000);
+ double average = tr.averageSteps();
+
+ boolean passed =
+ getResults(0.0, average, "averageSteps() returns 0.0 when no days recorded");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeDoubleResult()
+ {
+ StepTracker tr = new StepTracker(10000);
+ tr.addDailySteps(9000); // This is too few steps for the day to be considered active.
+ tr.addDailySteps(5000);
+ tr.addDailySteps(13000);
+ tr.addDailySteps(23000);
+ tr.addDailySteps(1111);
+ double average = tr.averageSteps();
+
+ boolean passed =
+ getResults(
+ 10222.2, average, "averageSteps() returns 10222.2 (no integer division)");
+ assertTrue(passed);
+ }
+ }
+
+Here is the rubric for the ``averageSteps`` method for this problem. Did you receive all the points? In class, your teacher may have you grade each others' code.
.. figure:: Figures/stepTrackerRubric4.png
:width: 700px
@@ -473,7 +697,3 @@ Here is the rubric for the averageSteps method for this problem. Did you receiv
:figclass: align-center
Figure 4: Rubric for averageSteps method
-
-
-
-
diff --git a/_sources/Unit5-Writing-Classes/Figures/FA19 FY Admit Phone Calling 4-2-19.csv b/_sources/Unit5-Writing-Classes/Figures/FA19 FY Admit Phone Calling 4-2-19.csv
deleted file mode 100644
index 31b495e73..000000000
--- a/_sources/Unit5-Writing-Classes/Figures/FA19 FY Admit Phone Calling 4-2-19.csv
+++ /dev/null
@@ -1,506 +0,0 @@
-Division,Major,Last Name,First Name,City,ST,Mobile Phone,Mobile Phone 2,Email,Current Status,Attending ASD
-Busines,ACC,Bielert,Morgan,Bristol,CT,860-378-9515,,mnb2001@sbcglobal.net,ACCEPT,
-Busines,ACC,Dutton,Carlene,East Longmeadow,MA,413-544-5911,,carlene.dutton@eastlongmeadowma.gov,ACCEPT,
-Busines,ACC,Jensen,Laura,Torrance,CA,310-408-8600,,1037298@etusd.org,ACCEPT,
-Busines,ACC,Kilmer,Amber,Springfield,MA,413-231-7661,,89659@cpsge.org,ACCEPT,
-Busines,ACC,Mabb,Zoe,Chicopee,MA,413-316-7815,,zmabb22@gmail.com,ACCEPT,
-Busines,ACC,Marchesseault,Ryan,New Boston,NH,603-486-8567,,ryan.marchesseault@gmail.com,ACCEPT,YES
-Busines,ACC,Melendez,Justin,Enfield,CT,860-394-6866,,justinsoccer9m@gmail.com,DEPOSIT,YES
-Busines,ACC,Mills,Madison,Atkinson,NH,603-489-7200,,mmills19@timberlane.net,ACCEPT,
-Busines,ACC,Moriarty,Devan,Springfield,MA,413-737-7035,413-262-0099,devanmoriarty@icloud.com,ACCEPT,
-Busines,ACC,Neth,Eli,Verona,NY,315-761-6068,,enethnba@gmail.com,ACCEPT,
-Busines,ACC,Perlmutter,Gwyneth,Springfield,MA,413-747-8689,413-317-4865,351gwyn@gmail.com,ACCEPT,
-Busines,ACC,Roberts,Nesta,Manchester,CT,860-532-8415,,19nesrob@mpspride.org,ACCEPT,
-Busines,ACC,Santos,Jacob,Holyoke,MA,413-504-8254,,jacobsantos699@gmail.com,ACCEPT,
-Busines,ACC,Smith,Leah,Sidney,ME,207-313-3470,,leah.e.smith.02@gmail.com,ACCEPT,
-Busines,ACC,Szwajkowski,Justin,Westhampton,MA,413-548-0217,,jszwajkowski19@gmail.com,ACCEPT,
-Busines,ACC,Whitehead,Haley,Chicopee,MA,413-388-8093,,haleylwhitehead@gmail.com,ACCEPT,
-Busines,BUS,Colon Lopez,Jean,Springfield,MA,413-505-3217,,cjeancarlos16@gmail.com,ACCEPT,
-Busines,ENT,Gleason,Haylee,Pittsfield,MA,413-770-6389,,hgleason955@gmail.com,ACCEPT,YES
-Busines,ENT,Leavitt,Caroline,Rancho Santa Fe,CA,858-353-5712,,carolineleavitt3@gmail.com,ACCEPT,
-Busines,ENT,Liedke,Collin,Newington,CT,860-491-4470,860-306-2307,cliedke@cox.net,ACCEPT,
-Busines,ENT,Rusinque,Brandon,Springfield,MA,413-285-9283,,brandonrusinque@gmail.com,ACCEPT,
-Busines,ENT,Thrash-Acevedo,Ajhalae,Canton,MA,617-504-5285,,ajhalae3@gmail.com,ACCEPT,YES
-Busines,HCM,Dulphe,Nehemie,Framingham,MA,508-308-5252,774-225-3437,ndulphe8009@fpsed.org,ACCEPT,
-Busines,HCM,Gonzalez,Margie,Hartford,CT,860-280-8998,,margiegonzalex16@gmail.com,ACCEPT,
-Busines,HCM,Gonzalez,Margie,Hartford,CT,860-804-6122,,margiegonzalex16@gmail.com,ACCEPT,
-Busines,HCM,Hollis,Jennifer,Dennis,MA,508-360-9157,,ejhollis19@gmail.com,ACCEPT,
-Busines,HCM,Lepore,Angelina,New London,CT,860-941-9965,,leporeangelina3@gmail.com,ACCEPT,
-Busines,HCM,Major,Nia,Springfield,MA,413-523-3107,,sirred6715@gmail.com,ACCEPT,
-Busines,HCM,Pellegrini,Elena,Ashland,MA,774-721-2016,,Pellegriniele@ashland.k12.ma.us,ACCEPT,
-Busines,HCM,Pulisz,Renee,Wallingford,CT,203-464-0391,,reneetwentytwo@gmail.com,ACCEPT,
-Busines,HCM,Renaudin,Annick,Cambridge,MA,781-518-8464,857-316-9817,renaudin.annick@yahoo.com,ACCEPT,
-Busines,HCM,Rivera,Stephanie,Springfield,MA,1-413-275-0141,,stephaniemrivera7@yahoo.com,ACCEPT,
-Busines,MGT,Barton,Dante,Gallup,NM,505-339-0793,,dantebarton00@gmail.com,ACCEPT,
-Busines,MGT,Cheng,Susan,Chicopee,MA,413-330-4781,,87068@cpsge.org,ACCEPT,
-Busines,MGT,Friedhaber,Brynn,Chicopee,MA,413-374-6296,,BrynnFriedhaber@gmail.com,ACCEPT,
-Busines,MGT,Gonzalez,Pamela,Pittsfield,MA,413-770-1386,,19pgonzalez@pittsfield.net,ACCEPT,
-Busines,MGT,Korcz,Ariana,Feeding Hills,MA,413-209-7531,,19akorcz@agawamed.org,DEPOSIT,YES
-Busines,MGT,Lee,Lawrence,Saraasota,FL,504-615-3916,,lawrence710ysl@gmail.com,ACCEPT,
-Busines,MGT,Martinez,Breisis,Houston,TX,832-441-3563,,Breisismartinez@gmail.com,ACCEPT,
-Busines,MGT,Nugent,Benjamin,North Haven,CT,203-694-4751,,bnugent2019@notredamehs.com,ACCEPT,
-Busines,MGT,Perrault,Mercedies,Waterboro,ME,207-209-3857,,mercediesperrault@rau57.org,ACCEPT,
-Busines,MGT,Renner,Hannah,Portland,CT,860-461-8895,,duststar860@gmail.com,ACCEPT,
-Busines,MGT,Slahtosky,Jason,South Windsor,CT,860-970-6846,,jcslahtosky@gmail.com,ACCEPT,
-Busines,MKT,Adarkwah,Hermish,Newington,CT,860-706-2503,,adarkwahhermish@gmail.com,ACCEPT,
-Busines,MKT,Bivans,Khetana,Windsor,CT,860-965-2746,,khetanab123@aol.com,ACCEPT,
-Busines,MKT,Browne-Ayala,Kiera,Boston,MA,617-980-8839,,Kierabrowneayala@gmail.com,ACCEPT,
-Busines,MKT,Clark,Samuel,Belchertown,MA,413-222-7958,,sam0417clark@gmail.com,ACCEPT,YES
-Busines,MKT,Crain,Catey,Hooksett,NH,603-661-9361,,cateycrain@gmail.com,ACCEPT,
-Busines,MKT,Crain,Catey,Hooksett,NH,603-674-0914,,cateycrain@gmail.com,ACCEPT,
-Busines,MKT,Goines,Cierrah,Bloomfield,CT,860-539-7031,,Cierrah123110@gmail.com,ACCEPT,
-Busines,MKT,McBride,Aidan,Ludlow,MA,413-575-5981,,aidanmcbride60@gmail.com,ACCEPT,
-Busines,MKT,Rivera,Anthony,Westfield,MA,413-847-0412,,imjustluigi777@gmail.com,ACCEPT,
-Busines,MKT,Seney,Lindsey,North Grosvenordale,CT,860-753-1691,,lindseyseney11@gmail.com,ACCEPT,
-Busines,MKT,Zyskowski,Victoria,Chicopee,MA,413-265-9578,,zyskowskivictoria@yahoo.com,ACCEPT,
-Busines,SPT,Chiota,Dominic,Orlando,FL,407-223-0597,,domchiota@gmail.com,ACCEPT,
-Busines,SPT,Cortis,Dakota,Barre,MA,413-324-3724,,kotacortis@gmail.com,ACCEPT,
-Busines,SPT,Lanese,James,Seymour,CT,203-231-5509,,jlanese74@gmail.com,DEPOSIT,YES
-Busines,SPT,Lathrop,Isaac,Jewett City,CT,860-608-8761,860-608-4576,newenglandfan88@icloud.com,ACCEPT,YES
-Busines,SPT,Looney,Bryson,Frisco,TX,214-574-9267,,brysonlooney81@gmail.com,ACCEPT,
-Busines,SPT,Lopes,Eric,Shelton,CT,203-954-9379,,ericl7328@gmail.com,ACCEPT,
-Busines,SPT,Martinez,Kamerin,Enfield,CT,860-967-7770,860-977-1495,KamerinMartinez12@yahoo.com,ACCEPT,
-Busines,SPT,McBride,Mariah,Enfield,CT,860-514-1767,,mariahm3290@gmail.com,ACCEPT,
-Busines,SPT,McKittrick,Catherine,East Longmeadow,MA,413-272-8835,,catherine.mckittrick@eastlongmeadowma.gov,DEPOSIT,YES
-Busines,SPT,Miket,Hunter,Torrington,CT,860-689-6061,,huntermiket@gmail.com,DEPOSIT,YES
-Busines,SPT,Orszulak,Travis,Ware,MA,413-813-5443,,travisorszulak23@gmail.com,ACCEPT,
-Busines,SPT,Ortiz,Leandra,Ridgewood,NY,917-685-5186,,leemagic12@gmail.com,ACCEPT,
-Busines,SPT,Rivera Colon,Isael,Hadley,MA,413-800-5028,,isael7074@gmail.com,DEPOSIT,
-Education,ECE,Casterline,Taylor,Westhampton,MA,413-358-1453,,tcasterline@smithtec.org,ACCEPT,
-Education,ECE,Cruz,Jolena,Springfield,MA,413-769-4096,,mlena9547@gmail.com,ACCEPT,
-Education,ECE,DeGrandpre,Madison,Florence,MA,413-923-2144,,madisondegrandpre@aol.com,ACCEPT,
-Education,ECE,Guerin,Lily,Belchertown,MA,413-386-8990,,lily.guerin@yahoo.com,DEPOSIT,
-Education,ECE,Rovatti,Felicity,Feeding Hills,MA,413-786-3439,,19frovatti@gmail.com,ACCEPT,
-Education,ECE,Rovatti,Felicity,Feeding Hills,MA,413-478-4052,,19frovatti@gmail.com,ACCEPT,
-Education,EDM,Cardonita,Giana,Guilford,CT,203-738-8366,,gigicardonita@att.net,ACCEPT,
-Education,EDM,Farrell,Margaret,Williamsburg,MA,413-262-0907,,mfarrell2019@gmail.com,ACCEPT,
-Education,EDM,Farrell,Margaret,Williamsburg,MA,413-369-8044,,mfarrell2019@gmail.com,ACCEPT,
-Education,EDM,Jasmin,Abigail,Pascoag,RI,401-871-6140,,ajgymnast31@gmail.com,ACCEPT,
-Education,EDM,Pelham,Sara,Milford,CT,203-499-7080,203-589-0089,pelhamsara@students.milforded.org,ACCEPT,
-Education,EDM,Skellett,Madison,Brooklyn,CT,860-617-7615,,mskellett2019@woodstockacademy.org,ACCEPT,
-Education,EDM,Somers,Hannah,Monson,MA,413-544-2712,,hannah1107@comcast.net,ACCEPT,
-Education,EDM,Toledo,Rebecca,Springfield,MA,413-348-4631,,htoledo20@comcast.net,ACCEPT,
-Education,ELE,Burke,Cedar,Rochester,NH,603-705-0532,,cedarrae@gmail.com,DEPOSIT,YES
-Education,ELE,Burke,Danielle,Springfield,MA,203-631-8607,,danielleburke1006@gmail.com,ACCEPT,
-Education,ELE,Cox,Alexia,Enfield,CT,860-993-3820,860-614-5347,lexicoxx9@gmail.com,ACCEPT,
-Education,ELE,Easton,Alissa,Southwick,MA,413-540-6264,,alissaeaston5@gmail.com,ACCEPT,
-Education,ELE,Esteban,Karla,Springfield,MA,413-523-6435,,karlases1011@gmail.com,ACCEPT,
-Education,ELE,Gangell,Laura,New Milford,CT,860-248-9319,,lgangell01@yahoo.com,ACCEPT,
-Education,ELE,Giroux,Jensen,Ludlow,MA,413-563-1146,413-388-6252,jessgroo@yahoo.com,ACCEPT,
-Education,ELE,Hess,Jillian,Southwick,MA,413-523-3268,,jillianhess15@gmail.com,ACCEPT,
-Education,ELE,Kajka,Sophia,East Longmeadow,MA,413-426-5492,,sophia.kajka@eastlongmeadowma.gov,ACCEPT,
-Education,ELE,Kelleher,Elizabeth,Springfield,MA,413-310-5502,,akelleher1969@gmail.com,ACCEPT,
-Education,ELE,Kida,Cassidey,South Hadley,MA,413-265-3592,,kidac@student.elms.edu,ACCEPT,
-Education,ELE,Labonte,Caroline,Agawam,MA,413-374-2907,,carelabonte@yahoo.com,ACCEPT,YES
-Education,ELE,Luis-Fuentes,Heidy,Bristol,CT,860-834-6302,,heidyluisfuentes@gmail.com,ACCEPT,
-Education,ELE,Ortendahl,Megan,Brockton,MA,774-277-1220,,meganortendahl13@gmail.com,ACCEPT,
-Education,ELE,Robillard,Jenna,Chicopee,MA,413-265-6826,,89651@cpsge.org,ACCEPT,YES
-Education,ELE,Santamore,Katelyn,Waitsfield,VT,802-505-3565,,katelynsantamore@gmail.com,ACCEPT,
-Education,ELE,Wegrzyn,Samantha,Chicopee,MA,413-306-7633,,samanthawegrzyn@outlook.com,ACCEPT,
-Education,ELE,Whittier,Hannah,Sutton,MA,508-414-5558,,horsefieldhockey@gmail.com,ACCEPT,
-Education,ESL,Elmokaddem,Fatima,Suffield,CT,860-794-1950,,fatima.elmokaddem@suffieldstudent.org,ACCEPT,
-Education,ESL,Schaefer-Calderon,Lillian,Three Rivers,MA,413-362-4140,,lschaefercalderon@gmail.com,ACCEPT,
-Education,SED,Furgal,Natanya,Chicopee,MA,720-660-2669,720-660-5161,natfurgal.vmc@gmail.com,DEPOSIT,YES
-Education,SED,Hinkle,Tabitha,Suffield,CT,860-308-6612,,jaist@frontier.com,ACCEPT,
-Education,SED,Jimenez,Andy,Worcester,MA,774-330-9486,,andyjimenez62@gmail.com,ACCEPT,
-Education,SED,Kennedy,Keegan,Seymour,CT,203-535-3565,203-500-0977,keegankennedy2@yahoo.com,DEPOSIT,YES
-Education,SED,Laflam,Grace,Easthampton,MA,413-992-9121,,laflamg.school@gmail.com,ACCEPT,
-Education,SED,McGuinness,Megan,Holyoke,MA,413-222-9459,,megmcguinness4@gmail.com,ACCEPT,
-Education,SED,Neal,Lucy,Hartford,CT,860-849-4290,,lucyneal2000@gmail.com,ACCEPT,
-Education,SED,Potter,Jovanna,New London,CT,860-772-7616,,jo.potter1@outloo.com,DEPOSIT,YES
-Education,SED,Stratman,Jacob,Uxbridge,MA,774-287-8257,,jakestratman19@gmail.com,ACCEPT,
-Education,SED,Van Tassel,Spencer,East Longmeadow,MA,413-218-4963,,spencer.vantassel@eastlongmeadowma.gov,ACCEPT,
-Humanities & Fine Arts,ENG,Leblanc,Olivia,Springfield,MA,413-209-2230,,oml6802001@gmail.com,ACCEPT,YES
-Humanities & Fine Arts,ENG,Rosario,Ruth,Springfield,MA,413-627-2134,,ruthie200113@gmail.com,ACCEPT,
-Humanities & Fine Arts,HIS,Blades,Annalee,Yuma,AZ,928-210-9664,928-345-8889,annalee.blades@yumacatholic.org,ACCEPT,
-Humanities & Fine Arts,HIS,Blain,Matthew,Belchertown,MA,413-544-1154,413-283-5180,Matrayblain@gmail.com,ACCEPT,
-Humanities & Fine Arts,HIS,Tippett,Caitlynn,Chicopee,MA,413-271-2118,,catippett99@gmail.com,ACCEPT,
-Humanities & Fine Arts,LBA,Helfenbein,Sara,Oakham,MA,508-330-9051,,bhelf@charter.net,ACCEPT,
-Humanities & Fine Arts,LBA,Wilson,Nyah,Dartmouth,MA,603-513-8841,508-717-7963,nwilson0222@gmail.com,ACCEPT,
-Undeclared,UND,Amoro,Alex,South Windsor,CT,860-869-9362,,alexamoro01@gmail.com,ACCEPT,
-Undeclared,UND,August,Michael,Stratford,CT,203-864-5734,203-610-4150,michaelaugu00@stratk12.org,ACCEPT,
-Undeclared,UND,Bellino,Peter,Woburn,MA,781-281-6174,,pmbellino00@gmail.com,ACCEPT,YES
-Undeclared,UND,Bushey,Kelsey,Hadley,MA,413-727-2082,,busheyk.2019@hadleyschools.org,ACCEPT,
-Undeclared,UND,Casanova,Dionn,Greenfield,MA,413-768-4189,,diocas119@gpsk12.org,ACCEPT,
-Undeclared,UND,Claude,Willritch,Framingham,MA,508-416-9001,,wclaude1086@fpsed.org,ACCEPT,
-Undeclared,UND,Clay,Makayla,Brimfield,MA,413-495-2068,,clayymakayla@gmail.com,ACCEPT,
-Undeclared,UND,Colombani,Adianez,Westfield,MA,413-777-7137,413-297-7930,acolombani05@gmail.com,ACCEPT,
-Undeclared,UND,Correia,Kimberlly,Oxford,MA,774-330-8915,508-353-4384,kimkimcorreia@hotmail.com,ACCEPT,
-Undeclared,UND,Craig,Alyssa,Wallingford,CT,203-999-4365,203-537-2819,7lysscra7@gmail.com,ACCEPT,
-Undeclared,UND,Demaral,Ryan,Raynham,MA,774-501-7442,,RyanDemaral2121@gmail.com,ACCEPT,
-Undeclared,UND,Dewey,Emily,Melrose,MA,617-955-0940,,egdewey519@gmail.com,ACCEPT,
-Undeclared,UND,Dukuray,Moindy,Chicopee,MA,413-930-5859,,moindy316@gmail.com,ACCEPT,
-Undeclared,UND,Filev-Mihalak,Emmanuela,Holyoke,MA,413-552-7128,,emmafilev@gmail.com,ACCEPT,
-Undeclared,UND,Fortunatti-Campbell,Jonah,Springfield,MA,510-407-3927,,Jfortunatti9@gmail.com,ACCEPT,
-Undeclared,UND,Francis,Adalena,Waterbury,CT,203-725-4129,,adalena4@comcast.net,DEPOSIT,YES
-Undeclared,UND,Goncalves,Davi'an,New Bedford,MA,774-297-0815,774-271-5396,daviangoncalves1@yahoo.com,ACCEPT,
-Undeclared,UND,Gourde,Elizabeth,Holyoke,MA,413-297-4597,,ekgift2003@gmail.com,ACCEPT,
-Undeclared,UND,Grendol,Prudence,Sutton,MA,774-276-7078,,prudence.g41@gmail.com,ACCEPT,
-Undeclared,UND,Guilmartin,Joshua,East Granby,CT,860-874-3520,860-305-9222,jguilmartin24@gmail.com,DEPOSIT,
-Undeclared,UND,House,Myah,Pittsfield,MA,413-411-8104,,mhouse@lenoxps.org,ACCEPT,
-Undeclared,UND,Jacobs,Lauren,Terryville,CT,860-845-4232,860-940-7849,jacobl19@plymouthschools.us,ACCEPT,
-Undeclared,UND,Jardine,Elizabeth,Rutland,MA,508-414-9791,,Liz.Jardine@yahoo.com,ACCEPT,
-Undeclared,UND,Johnson,Mallorie,Tolland,CT,860-657-6575,,malloriejohnson50842@tolland.k12.ct.us,ACCEPT,
-Undeclared,UND,Jones,Natalie,West Springfield,MA,413-209-7268,,wnc367@gmail.com,ACCEPT,
-Undeclared,UND,Kaczor,Philip,Chicopee,MA,413-777-8020,,rjkaczor@yahoo.com,ACCEPT,
-Undeclared,UND,Kalbaugh,Meghan,Chicopee,MA,413-355-0205,,makalbaugh@gmail.com,ACCEPT,
-Undeclared,UND,Maxwell,Olivia,Naugatuck,CT,203-217-7551,,cats1068max@gmail.com,ACCEPT,
-Undeclared,UND,McCoy,Joseph,Springfield,MA,413-887-9357,,Jmmccoy224@gmail.com,ACCEPT,
-Undeclared,UND,Morgan,Jonathan,Bloomfield,CT,860-478-1352,860-938-8259,morganjonny08@gmail.com,ACCEPT,
-Undeclared,UND,Nodell,Ryan,Monson,MA,413-544-4525,,nodellryan@gmail.com,ACCEPT,
-Undeclared,UND,Nsafoah,Eugenia,Worcester,MA,774-696-0578,,nsafoaheugene@gmail.com,ACCEPT,
-Undeclared,UND,Nwadike,Monica,Roxbury,MA,617-953-3102,,monicanwadike567@gmail.com,ACCEPT,
-Undeclared,UND,O'Connor,Riley,Florence,MA,413-588-5022,,riley.oconnor@stu.northampton-k12.us,ACCEPT,
-Undeclared,UND,Patel,Parth,Palmer,MA,413-231-6342,,parthgpatel7@gmail.com,ACCEPT,
-Undeclared,UND,Poulton,Rachel,Brunswick,ME,207-844-3862,,raepoulton@gmail.com,ACCEPT,
-Undeclared,UND,Roc,Jonte,Seymour,CT,475-777-6022,,y0ung_reezy89@icloud.com,ACCEPT,
-Undeclared,UND,Schmarr,Kailey,Southington,CT,860-471-0075,,kailschmarr@gmail.com,ACCEPT,
-Undeclared,UND,Shah,Halimah,Springfield,MA,413-309-8188,,hshah@hampdencharter.org,ACCEPT,
-Undeclared,UND,Slahtosky,Jacob,South Windsor,CT,860-595-7084,,jslahtosky@kelsercorp.com,ACCEPT,
-Undeclared,UND,Velasquez,Ashley,Providence,RI,401-699-1490,,ashleyv924@icloud.com,ACCEPT,
-Undeclared,UND,Weston,Eliza,Cromwell,CT,860-754-4719,,elizawestonn@hotmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Abekah,Queenstar,Pittsfield,MA,413-358-8049,413-212-2767,19qabekah@pittsfield.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Al-Aziz,Cizara,Fitchburg,MA,978-503-4561,,calaziz@student.fitchburgschools.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Ball,Mikayla,Epping,NH,603-303-4885,,mball@eppingsd.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Bass,Julian,Springfield,MA,413-273-9850,,Splashking1330@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Bedor,Keisha,St. Johnsbury,VT,802-535-5559,,kb279050@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Brill,Kayla,New Boston,NH,603-325-1894,,brillkayla1@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Buckhout,Lilian,San Diego,CA,619-602-5265,,buckhoutlily@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Calafiore,Isabella,Rocky Hill,CT,860-593-1460,860-593-1510,santoc62@sbcglobal.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Caraballo,Natalia,Arlington,TX,787-414-3120,,natycaraballo00@gmail.com,DEPOSIT,
-"Natural Sciences, Mathematics & Technology",BIO,Castro,Irma,Harvey,LA,504-320-9437,,irmacastro01@hotmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Colon,Lilivette,Westfield,MA,413-330-6746,,Lilivettec82901@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Coulibaly,Issa,Bronx,NY,347-280-0447,718-320-4339,issa.coulibaly@bronxdalehs.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Cristian,Michelle,Worcester,MA,508-718-7169,508-579-3082,mcristian2115@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Cullinane,Erin,Broad Brook,CT,860-374-8358,,cull.erin@aol.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,D'Angelo,Hannah,Warren,MA,413-813-7060,,hannahdangelocollege@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,De Oliveira,Vitoria,Framingham,MA,508-371-6473,,vdeoliveira25@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Dejesus Brown,Gabriella,New Britain,CT,860-712-3411,,gdejesusbrown@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Fielding,Bria,New London,CT,(1860) 271-5091,,briafielding@icloud.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Foley,Jack,Burlington,CT,860-384-9776,,jfoleyyy05@yahoo.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Fontaine,Madelyn,South Hadley,MA,413-522-0771,,maddieraef4@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Garcia-Ramirez,Litzy,Bridgeport,CT,203-727-0616,,litzy0988@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Generali,Gabrielle,Waterbury,CT,860-372-9628,,gabriellagenerali@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Gettings,Julia,Bristol,CT,860-885-4510,,juliagettings4@outlook.com,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Glasheen,Mary,Holyoke,MA,413-210-3344,,maryg0896@holyokestudents.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Hamid,Mustafa,Chicopee,MA,413-557-9907,,hamidmustafa671@yahoo.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Harris,Joy,Bristol,CT,860-989-7994,860-944-5033,19harrisjoy@bristolk12.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Hassan,Hawraa,Stone Mountain,GA,404-916-7655,,hawraahassan@fugeesacademy.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Houle,Jordan,South Hadley,MA,413-330-3746,413-275-3004,jordanhoule13@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Ivancev,Victor,Greenfield,MA,413-834-5347,,vdivancev@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",BIO,James,Gahbrielle,Worcester,MA,508-615-9552,,gahbrielle.james2000@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Kidd,Samari,Holyoke,MA,413-693-4209,413-777-6529,samarik0873@holyokestudents.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Kouao,Seyvon,Pittsfield,MA,413-770-8518,,19skouao@pittsfield.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Kuplast,Cassandra,Southampton,MA,413-727-5031,,scooterf16@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Lafleur,Kiana,Torrington,CT,860-201-7944,203-676-5454,kianalafl@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Laviolette,Naomi,West Springfield,MA,413-328-4308,,naomi.rae890@icloud.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Leduc,Morgan,Dudley,MA,508-277-0226,,morganleduc28@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Legault-Ross,Lena,Riverside,RI,401-516-1270,,lena.legault-ross@bayviewacademy.org,DEPOSIT,
-"Natural Sciences, Mathematics & Technology",BIO,Maldonado,Marelyne,Springfield,MA,413-271-2888,,marelyne.maldonado@yahoo.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Mayhew,Marissa,Huntington,MA,413-685-5359,,marissam2911@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,McCarthy,Aimee,Ashford,CT,860-617-8849,,Aim0905@Charter.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,McMahon,Sarah,Pittsfield,MA,413-281-1349,,mcmahonsarah140@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Middleton,Helena,Holyoke,MA,413-313-8764,,hlmiddleton28@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Moniz,Sarah,Brockton,MA,774-360-4143,,sarahmoniz13@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Monroe,Morgan,Rowley,MA,978-821-7274,,morgan.monroe1220@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Moriarty,Anna,South Hadley,MA,413-533-1323,413-539-8179,annajm4@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Mullen,Heaven,Laplace,LA,859-536-3005,,demullen@att.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Nguyen,Truong,New Orleans,LA,504-491-2928,,stu.troung.nguyen@insnola.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Ortiz,Ivana,Springfield,MA,413-316-0187,,ivanaortiz18@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Paige,Samantha,Rochester,VT,802-431-7075,,spaige19@acsdvt.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Paquette,Ariana,Enosburg Falls,VT,802-393-7148,,ari.paq7@gmail.com,DEPOSIT,
-"Natural Sciences, Mathematics & Technology",BIO,Planter,Morrigan,Holyoke,MA,413-250-1584,,mplanter2019@macduffie.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Radi,Zaineb,Chicopee,MA,413-557-8663,,radi.zaineb1223@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Rogers,Erica,Springfield,MA,413-886-4700,,ericarogers662@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Santos,Natalia,Southbridge,MA,774-452-1283,,nataliasantos050401@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Skoczylas,Matthew,Suffield,CT,860-967-6558,,matthew.skoczylas@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Tartaglia,Richard,Rehoboth,MA,774-991-0868,,rtartaglia2019@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Tejeda Hernandez,Perla,Roxbury,MA,857-829-7687,857-234-5217,perlatejeda19@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Thang,Sunday,Stone Mountain,GA,678-752-7401,,sundaythang@fugeesacademy.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Toolan,Melina,Vernon,CT,860-532-9534,,melina.toolan@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Valentin,Amy,Springfield,MA,413-219-0711,,amyanisha@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Vicente,Gladys,Norwalk,CT,203-820-8595,203-822-4484,vicentegladys22@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Vona,Amanda,East Longmeadow,MA,413-324-3338,,avona01@charter.net,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Walker,Erika,Pigeon Forge,TN,865-660-4932,,nicholewalker67@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Waters,Ja'lin,Waterbury,CT,203-768-2412,,jalin.waters@icloud.com,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",BIO,Waters,Lily,Middlefield,MA,413-207-2007,,waterslily23@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Wenz,Khylyn,Palmer,MA,413-530-8619,,khywenz@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",BIO,Xavier,Tiago,Malden,MA,781-666-0350,,txavier@student.popejohnhs.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CHE,Rodriguez,Samantha,Chicopee,MA,413-388-7254,,samanthaxxrodriguez@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CHE,Sullivan,Alexa,Wilbraham,MA,413-478-1189,,stu360.asullivan@ludlowps.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Delion,Sebastian,Springfield,MA,413-784-3011,,sebastiandelion14@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Elsayed,Mohamed,Springfield,MA,413-636-9064,413-883-7386,melsayed@hampdencharter.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Henn,Ryan,Danbury,CT,203-240-9009,,rhenn@myimmaculatehs.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Htet,Aung,Clarkston,GA,470-435-2744,,aunghtet@fugeesacademy.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Judd Rose,Parker,Citrus Heights,CA,916-547-9339,,parkerjuddrose@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",CIT,Lucey,Ethan,Florence,MA,413-588-4032,,elucey88@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Perry,Ryan,Holyoke,MA,413-218-8512,,ryanp40101@gmail.com,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",CIT,Sum,Pau,Clarkston,GA,404-207-8273,,pausum@fugeesacademy.org,DEPOSIT,
-"Natural Sciences, Mathematics & Technology",CIT,Van Tassel,Evan,East Longmeadow,MA,413-218-4247,,shroomboom9@gmail.com,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",CIT,Vazquez,Miguel,Chicopee,MA,413-777-9967,413-888-7609,miguelAvazquez1347@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Win,Tin,Stone Mountain,GA,404-952-9554,,tinwin@fugeesacademy.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",CIT,Yoo,Ryan,Northampton,MA,413-801-5607,,ryoo2317@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",GDS,Horn,Aubrey,West Hartford,CT,860-712-8364,,aubreyhorn612@gmail.com,ACCEPT,
-"Natural Sciences, Mathematics & Technology",GDS,Kenneson,Mikayla,Chicopee,MA,413-315-8365,413-883-4001,m_k_rhayne@yahoo.com,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",GDS,Martin,Jarrett,New Hartford,CT,860-460-6031,,jarrettmartin0103@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",GDS,Miller,Logan,Lunenburg,MA,978-400-8839,,millerl@sizerschool.org,ACCEPT,
-"Natural Sciences, Mathematics & Technology",GDS,Prescott,Matthew,Ware,MA,774-200-6662,413-427-3971,mattuUwU1029@gmail.com,ACCEPT,YES
-"Natural Sciences, Mathematics & Technology",GDS,Torres,China,Waterbury,CT,203-819-0434,,alexichina11@gmail.com,DEPOSIT,
-"Natural Sciences, Mathematics & Technology",GDS,Tufano,Grace,Stamford,CT,203-536-9989,,graceyg@optonline.net,DEPOSIT,YES
-"Natural Sciences, Mathematics & Technology",GDS,Waldron,Luke,Torrington,CT,860-480-1591,,lwaldron@rsdg.org,DEPOSIT,
-Social Sciences,CRJ,Alves,Thomas,Ludlow,MA,413-324-6298,,stu0037.talves@ludlowps.org,ACCEPT,
-Social Sciences,CRJ,Avila,Dayana,Chelsea,MA,617-669-8310,,dayaavila287@gmail.com,ACCEPT,
-Social Sciences,CRJ,Boulay,Sammantha,Auburn,NH,603-657-4221,603-244-9175,sammanthaboulay@trinity-hs.org,ACCEPT,
-Social Sciences,CRJ,Brown,Megan,Winchendon,MA,978-727-9480,,brownmm@sizerschool.org,ACCEPT,
-Social Sciences,CRJ,Brown,Paul,Mesa,AZ,480-440-0409,480-309-2969,Massillontiger177@gmail.com,ACCEPT,
-Social Sciences,CRJ,Canapari,Alexis,Waterbury,CT,203-707-8186,,alexis122101@gmail.com,ACCEPT,
-Social Sciences,CRJ,Canapari,Alexis,Waterbury,CT,203-592-4115,,alexis122101@gmail.com,ACCEPT,
-Social Sciences,CRJ,Cantela,Cheyenne,Chicopee,MA,413-240-8977,,cheyennecantela16@gmail.com,ACCEPT,
-Social Sciences,CRJ,Coletti,Maria,St. Petersburg,FL,727-557-7209,,maria.17coletti@gmail.com,ACCEPT,
-Social Sciences,CRJ,Collazo,Kelsey,Springfield,MA,413-273-2336,,kelseykiabeth@gmail.com,ACCEPT,
-Social Sciences,CRJ,Concepcion,Giovanna,Springfield,MA,413-331-9890,,concepciongiovanna@gmail.com,ACCEPT,
-Social Sciences,CRJ,Da Rocha,Douglas,Tyngsboro,MA,978-876-7178,,douglasdzr@hotmail.com,ACCEPT,
-Social Sciences,CRJ,Dickson,Jah'anesty,Springfield,MA,413-539-0202,,jahanestydickson@gmail.com,ACCEPT,
-Social Sciences,CRJ,Disimile,McKenzee,Springfield,MA,413-219-7932,,disimile@hampdencharter.org,ACCEPT,
-Social Sciences,CRJ,Dudley-Acevedo,Jadesi,Meriden,CT,860-807-5921,,jadesidudley@gmail.com,ACCEPT,
-Social Sciences,CRJ,French-Graham,Nadia,Waterbury,CT,203-578-5209,,french-graham.nadia@holycrosshs-ct.com,ACCEPT,YES
-Social Sciences,CRJ,Jackson,Lataja,Hartford,CT,860-888-1846,860-888-1755,2019latajaj344@student.whps.org,ACCEPT,YES
-Social Sciences,CRJ,Jarvis,Brandon,Springfield,MA,413-726-8151,,90057@cpsge.org,DEPOSIT,YES
-Social Sciences,CRJ,Jennings,Madison,Milford,CT,203-306-6156,,jenningsmadison@students.milforded.org,ACCEPT,YES
-Social Sciences,CRJ,Martinez,Angel,Waterbury,CT,203-519-1454,,angelmartinez1023@aol.com,ACCEPT,
-Social Sciences,CRJ,Martinez,Angel,Waterbury,CT,203-519-1475,,angelmartinez1023@aol.com,ACCEPT,
-Social Sciences,CRJ,Martins,Anna Clara,Taunton,MA,508-468-1533,508-468-5694,annayellow2010@icloud.com,ACCEPT,
-Social Sciences,CRJ,Mejias,Veronica,Meriden,CT,203-715-0921,,mejiasxvee@gmail.com,ACCEPT,
-Social Sciences,CRJ,Nieves,Nadia,Westfield,MA,413-386-8865,,nadia.nieves214@gmail.com,ACCEPT,
-Social Sciences,CRJ,O'Neal,Nya,Springfield,MA,413-221-4868,,nyaoneal@yahoo.com,ACCEPT,
-Social Sciences,CRJ,Ortiz-Ruiz,Kiara,Willimantic,CT,860-208-2437,,kiaralizruiz24@gmail.com,ACCEPT,
-Social Sciences,CRJ,Palmer,Trinity,Willimantic,CT,860-634-3623,,trinitypalmer90@gmail.com,ACCEPT,
-Social Sciences,CRJ,Poppel,Danielle,Windsor Locks,CT,860-550-5982,860-519-7172,poppel.danielle@student.wlps.org,ACCEPT,YES
-Social Sciences,CRJ,Sheehan,Ryan,Ludlow,VT,802-345-9220,,sheehanryanbr23@gmail.com,ACCEPT,
-Social Sciences,CRJ,St. Julien,Tia,Springfield,MA,413-686-0165,,arrow1flash2@gmail.com,ACCEPT,
-Social Sciences,CRJ,Thomas,Tynisha,New Haven,CT,203-435-0299,,thomastynisha01@gmail.com,ACCEPT,
-Social Sciences,CRJ,Tran,Kim,Manchester,NH,603-854-2201,,kim.tran@trinity-hs.org,ACCEPT,
-Social Sciences,CSD,Borla,Taylor,Southington,CT,860-301-3180,,taylor.borla@gmail.com,DEPOSIT,
-Social Sciences,CSD,Carrizales,Rebeka,Alamo,TX,956-588-7912,956-223-9731,rebekacarrizales2019@gmail.com,ACCEPT,
-Social Sciences,CSD,Cormier,Monique,Leominster,MA,978-407-7838,,monique.e.cormier@gmail.com,DEPOSIT,YES
-Social Sciences,CSD,Gagnon,Casey,Stoughton,MA,617-615-1552,,ceg25@msn.com,DEPOSIT,YES
-Social Sciences,CSD,Gonzalez,Stefany,Chicopee,MA,413-570-6301,,153480@cpsge.org,DEPOSIT,
-Social Sciences,CSD,Guberow,Luiza,South Hadley,MA,413-388-5759,,lguberow@gmail.com,DEPOSIT,
-Social Sciences,CSD,Kenyon,Margaret,East Lyme,CT,860-373-5510,,margaritack1104@gmail.com,ACCEPT,
-Social Sciences,CSD,Mannino,Marianna,New Salem,MA,978-467-7802,,mariannamannino@yahoo.com,ACCEPT,
-Social Sciences,CSD,McFarlane,Tiara,Stoughton,MA,617-365-5447,,tmcfarlane405@stoughtonschools.org,ACCEPT,
-Social Sciences,CSD,Mejia,Amarantha,Los Angeles,CA,323-359-6747,,amaranthamm@gmail.com,ACCEPT,
-Social Sciences,CSD,Mejia,Amarantha,Los Angeles,CA,323-399-0619,,amaranthamm@gmail.com,ACCEPT,
-Social Sciences,CSD,O'Callaghan,Grace,Waltham,MA,781-697-7040,781-795-2607,gracieeoc@yahoo.com,ACCEPT,
-Social Sciences,CSD,Pope,Lauren,Belchertown,MA,413-231-0486,413-250-0483,laurenp7065@gmail.com,DEPOSIT,YES
-Social Sciences,CSD,Rivera,Natalia,Southington,CT,860-877-5764,860-517-6213,nataliarsophie@gmail.com,ACCEPT,
-Social Sciences,CSD,Rodrigues,Haylee,Ludlow,MA,413-335-7552,,haylee357@gmail.com,DEPOSIT,YES
-Social Sciences,CSD,Roy,Madison,Fairhaven,MA,774-510-0604,,acting431@icloud.com,ACCEPT,
-Social Sciences,CSD,Sabia,Jenna,Stratford,CT,203-554-6388,,sabia796@gmail.com,ACCEPT,
-Social Sciences,CSD,Strycharz,Emily,Monson,MA,413-563-2261,,emilyjane0501@hotmail.com,ACCEPT,
-Social Sciences,PSY,Abbott,Oliver,Granby,MA,413-654-8555,,tnobabbott@gmail.com,DEPOSIT,
-Social Sciences,PSY,Ayala,Nicholas,Springfield,MA,413-222-0923,,aa.nicholas11@gmail.com,ACCEPT,
-Social Sciences,PSY,Bailey-Provencher,Jacob,Hampden,MA,413-427-2402,,jacobbailey104@gmail.com,ACCEPT,
-Social Sciences,PSY,Barton,Trinity,Gardner,MA,978-490-0350,,trinityofficial@yahoo.com,DEPOSIT,YES
-Social Sciences,PSY,Bertoli,Veronica,Torrington,CT,860-989-1291,,veronicalbertoli@gmail.com,ACCEPT,
-Social Sciences,PSY,Blake,Jade,Ludlow,MA,413-575-9273,,jademblake47@gmail.com,ACCEPT,
-Social Sciences,PSY,Brantley,Jay'lla,Hamden,CT,203-589-6681,,jay'llabrantley10@icloud.com,ACCEPT,
-Social Sciences,PSY,Cody,Niah,Belchertown,MA,413-409-0211,,niahc1223@gmail.com,ACCEPT,
-Social Sciences,PSY,Colon,Tatiana,Springfield,MA,413-342-7187,,tatiana_14@icloud.com,ACCEPT,
-Social Sciences,PSY,Curtis,Erin,Windsor,CT,860-840-1733,,erincnails@gmail.com,ACCEPT,
-Social Sciences,PSY,Hamel,Angela,Chicopee,MA,413-575-7291,,angelahamel@gmail.com,ACCEPT,
-Social Sciences,PSY,Harrold,Kateri,North Brookfield,MA,774-452-6780,,katieharrold2373@yahoo.com,ACCEPT,
-Social Sciences,PSY,Jewell,Rachael,Springfield,MA,413-777-3281,,rachaeljewell11@gmail.com,ACCEPT,
-Social Sciences,PSY,Kirby,Emily,Peabody,MA,781-715-4880,781-715-3442,emily.kirby64@gmail.com,ACCEPT,
-Social Sciences,PSY,Kocot,Kaylin,Conway,MA,413-588-4324,413-369-4354,kaylinkocot@icloud.com,ACCEPT,
-Social Sciences,PSY,Kraft,Sarah,Springfield,MA,413-222-5422,413-459-8140,sarahkraft9@gmail.com,ACCEPT,
-Social Sciences,PSY,Lloyd,Cecelia,South Hadley,MA,413-654-7755,,cecelloyd27@gmail.com,ACCEPT,YES
-Social Sciences,PSY,Marrow,Malena,Ludlow,MA,413-883-5824,413-883-5872,lenamarrow@gmail.com,ACCEPT,YES
-Social Sciences,PSY,Maye,Emmanuel,Springfield,MA,413-726-8794,,kanyesouth@icloud.com,ACCEPT,
-Social Sciences,PSY,Miller,Jennifer,Maynard,MA,774-417-9976,,jennifermaeedebramiller@gmail.com,ACCEPT,
-Social Sciences,PSY,Nieves-Luna,Cristal,Worcester,MA,508-736-3872,774-479-8853,lunnaaxo1@icloud.com,ACCEPT,
-Social Sciences,PSY,Parker,Marissa,New London,CT,860-333-4656,,marissanparker4@gmail.com,ACCEPT,
-Social Sciences,PSY,Phillips,Casey,Davenport,IA,563-340-3937,563-340-2927,kcphil00137@gmail.com,ACCEPT,
-Social Sciences,PSY,Platt,Hannah,Southington,CT,860-681-6942,,h.jkplatt1@cox.net,ACCEPT,
-Social Sciences,PSY,Rodriguez,Ilani,Springfield,MA,413-693-9244,413-417-3806,ilanirod14@gmail.com,DEPOSIT,
-Social Sciences,PSY,Sakowicz,Amanda,Monson,MA,203-400-3162,,sakowicz121100@gmail.com,ACCEPT,
-Social Sciences,PSY,Shea,Brooke,West Brookfield,MA,774-641-6289,,bshea1233@gmail.com,ACCEPT,
-Social Sciences,PSY,Spada,Peter,Woodstock,CT,860-933-0191,,pspadahr@gmail.com,ACCEPT,
-Social Sciences,PSY,Tedeschi,Caitlin,East Longmeadow,MA,413-262-4892,,ctedeschi923@gmail.com,ACCEPT,
-Social Sciences,PSY,Torres,William,Springfield,MA,413-273-3446,,williamntorres14@gmail.com,ACCEPT,
-Social Sciences,PSY,Viruet,Javette,Hartford,CT,860-818-4450,,javettev@gmail.com,ACCEPT,
-Social Sciences,SOC,Mallory,Akeme,Amherst,MA,413-362-6978,,malloryar@gmail.com,ACCEPT,
-Social Sciences,SWK,Barrow,Paige,Adams,MA,413-418-2161,,paigebarrow14@gmail.com,ACCEPT,YES
-Social Sciences,SWK,Golden,Caitlin,Hampton,CT,860-933-3564,860-377-0195,caitlin.a.golden@gmail.com,ACCEPT,
-Social Sciences,SWK,Hopson,Abre'ana,Westwego,LA,504-758-7602,,stu.abre'ana.hopson@insnola.org,ACCEPT,
-Social Sciences,SWK,Laureano,Jillian,South Hadley,MA,413-923-1570,,jillelise319@gmail.com,DEPOSIT,YES
-Social Sciences,SWK,Lopez,Alexander,Chicopee,MA,413-454-7549,,ajlop2013@gmail.com,ACCEPT,
-Social Sciences,SWK,Palmer,Lili,Torrington,CT,860-938-3255,959-202-1074,lili.marie1241@gmail.com,ACCEPT,
-Social Sciences,SWK,Sheff,Milo,Manchester,CT,860-597-1159,,19milshe@mpspride.org,ACCEPT,YES
-Social Sciences,SWK,Stanton,Allison,Southington,CT,860-877-8111,,alliestranton01@gmail.com,ACCEPT,
-Social Sciences,SWK,Ynfante Luciano,Vidaly,Springfield,MA,413-883-5025,,vidanly12@gmail.com,ACCEPT,
-Nursing,NUR,Adams,Courtney,Westfield,MA,413-531-4785,,courtneyadams7@aol.com,DEPOSIT,YES
-Nursing,NUR,Adams,Madison,Springfield,MA,413-459-8167,413-726-5296,madisonadams413@gmail.com,ACCEPT,
-Nursing,NUR,Agli,Emma,Plantsville,CT,860-681-4411,,emma66@cox.net,DEPOSIT,
-Nursing,NUR,Aitken,Sarah,Pittsfield,MA,413-464-1458,,sarahaitken417@gmail.com,ACCEPT,YES
-Nursing,NUR,Allder,Rebecca,Little Compton,RI,401-439-9369,401-439-1780,allderr19@portsmouthschoolsri.org,ACCEPT,YES
-Nursing,NUR,Angiletta,Shawn,Meriden,CT,203-535-2643,,shawnangiletta@gmail.com,ACCEPT,
-Nursing,NUR,Archambault,Kayla,Brimfield,MA,(1508) 344-5038,,archambaultkayla@gmail.com,ACCEPT,
-Nursing,NUR,Armstrong,Jaylyn,North Grosvenordale,CT,860-420-8306,,jaylynarmstrong@yahoo.com,ACCEPT,
-Nursing,NUR,Barnard,Emma,Southwick,MA,413-886-9488,,emmabarnard52@gmail.com,ACCEPT,YES
-Nursing,NUR,Basa,Ann Frances Leig,West Springfield,MA,413-386-0284,,annbasa01@yahoo.com,ACCEPT,
-Nursing,NUR,Bates,Kendal,Hampden,MA,413-439-5542,,kendalchristine13@gmail.com,ACCEPT,
-Nursing,NUR,Bautista,Reyna,Springfield,MA,413-886-9994,,reynabautista151@gmail.com,ACCEPT,
-Nursing,NUR,Bell,Hailey,Springfield,MA,413-275-6054,413-433-9024,haileybell39@gmail.com,ACCEPT,
-Nursing,NUR,Bilodeau,Anna,Bridgewater,MA,508-631-4239,,annabilodeau2@gmail.com,ACCEPT,
-Nursing,NUR,Birks,Jenna,Belchertown,MA,413-544-2701,413-348-2213,jennabirks1@gmail.com,ACCEPT,
-Nursing,NUR,Bonak,Rachel,Shutesbury,MA,413-658-4880,,rachelbonak@gmail.com,ACCEPT,YES
-Nursing,NUR,Briones,Alyssa,West Springfield,MA,413-241-9459,,alyssabriones1109@gmail.com,ACCEPT,
-Nursing,NUR,Brooks,Kathleen,Chicopee,MA,413-433-5888,413-234-5025,90114@cpsge.org,ACCEPT,
-Nursing,NUR,Burke,Jessica,Ware,MA,413-324-6049,,jess.burke4@aol.com,ACCEPT,
-Nursing,NUR,Butler,Emily,West Springfield,MA,(1413) 636-3412,,ejbutler987@gmail.com,ACCEPT,
-Nursing,NUR,Cadena,Miranda,Enfield,CT,860-308-5387,,cadenamiranda@yahoo.com,ACCEPT,
-Nursing,NUR,Carmon,Alexandria,Pittsfield,MA,413-464-4275,,19acarmon@pittsfield.net,DEPOSIT,YES
-Nursing,NUR,Carra,Madison,Feeding Hills,MA,413-388-4666,,madcar01@comcast.net,DEPOSIT,YES
-Nursing,NUR,Castanho,Daniella,Rocky Hill,CT,860-218-5111,,castanhod@rockyhillps.com,ACCEPT,
-Nursing,NUR,Cedrone,Cristina,Westwood,MA,781-752-7404,,crissyc2@verizon.net,ACCEPT,
-Nursing,NUR,Childs,Yasmine,Wolcott,CT,203-232-1002,,ychilds138@gmail.com,ACCEPT,
-Nursing,NUR,Christie,Emily,Enfield,CT,860-899-8749,,emilyychristie@yahoo.com,DEPOSIT,YES
-Nursing,NUR,Ciambriello,Alexis,Brockton,MA,508-840-8207,774-381-4079,alexisciambriello@icloud.com,ACCEPT,
-Nursing,NUR,Cintron,Brian,Springfield,MA,413-218-7295,,briancintronnn@gmail.com,DEPOSIT,YES
-Nursing,NUR,Clare,Kelly,South Hadley,MA,413-221-8474,,kclaree27@gmail.com,DEPOSIT,YES
-Nursing,NUR,Clark,Mikayla,Hampden,MA,413-636-3897,,mikaylamclark@gmail.com,ACCEPT,
-Nursing,NUR,Cofsky,Katie,Sutton,MA,774-287-2898,,katiecofsky@yahoo.com,DEPOSIT,YES
-Nursing,NUR,Cope,Audrianna,Ludlow,MA,413-237-8142,,stu2211.acope@ludlowps.org,DEPOSIT,YES
-Nursing,NUR,Costello,Mikayla,Southington,CT,860-919-2348,,mikayla0705@cox.net,DEPOSIT,YES
-Nursing,NUR,Costello,Rosemary,Chicopee,MA,413-887-4155,,rosiexcostello@gmail.com,ACCEPT,YES
-Nursing,NUR,Cronkhite,Ashley,Lewiston,ME,207-844-0021,,ashleycronkhite@icloud.com,ACCEPT,YES
-Nursing,NUR,Crossman,Sarah,Millbury,MA,774-287-3938,,crossmansarah1@gmail.com,ACCEPT,
-Nursing,NUR,Curran,Caitlin,Harwinton,CT,860-806-1025,860-605-6518,caitlincurran6@gmail.com,DEPOSIT,YES
-Nursing,NUR,Danio,Sara,South Hadley,MA,413-265-1430,,saradanio1004@gmail.com,DEPOSIT,
-Nursing,NUR,Daughdrill,Spencer,Easthampton,MA,413-923-2881,,spdaughdrill@gmail.com,DEPOSIT,
-Nursing,NUR,DeFeo,Nicole,Watertown,CT,860-417-9465,,ndefeo87@yahoo.com,DEPOSIT,YES
-Nursing,NUR,Dekyong,Tenzin,East Rutherford,NJ,201-951-9600,,dekyongt3257@bectonhs.org,DEPOSIT,
-Nursing,NUR,Delmonte,Marissa,Chicopee,MA,413-887-9410,413-887-4646,101822@cpsge.org,DEPOSIT,
-Nursing,NUR,Depina,Mikyle,New Britain,CT,860-879-8786,,depinamikyle@gmail.com,ACCEPT,
-Nursing,NUR,Desrosiers,Madison,Enfield,CT,860-372-2512,,madisondesrosiers0215@gmail.com,ACCEPT,
-Nursing,NUR,Devries,MacKenzie,Monson,MA,413-335-4841,,mackenzie13marilyn@gmail.com,ACCEPT,
-Nursing,NUR,Dielli,Angela,Waterford,CT,860-865-8607,,angelatdielli@gmail.com,ACCEPT,
-Nursing,NUR,Disbrow,Zakary,Meriden,CT,203-213-4533,,zakarydisbrow@gmail.com,ACCEPT,
-Nursing,NUR,Dolan,Catherine,Saunderstown,RI,401-749-3707,401-667-0961,catherine_dolan@students.nksd.net,ACCEPT,
-Nursing,NUR,Donahue,Kiley,Winchendon,MA,978-895-7832,,dk13961@montytech.net,ACCEPT,
-Nursing,NUR,Donahue,Kiley,Winchendon,MA,978-895-3766,,dk13961@montytech.net,ACCEPT,
-Nursing,NUR,Dupras,Shaina,Brockton,MA,508-930-9641,,shainadupras@aol.com,DEPOSIT,YES
-Nursing,NUR,Ebrahim,Rawan,Feeding Hills,MA,413-977-6097,413-209-1049,ebrahimrawan@gmail.com,ACCEPT,YES
-Nursing,NUR,Elmer,Olivia,Shaftsbury,VT,802-375-5855,,olivia.elmer@icloud.com,ACCEPT,
-Nursing,NUR,Elsayyad,Ali,Northborough,MA,774-267-1483,744-253-3317,19elsayyad@gmail.com,ACCEPT,
-Nursing,NUR,Esten,Monica,Enfield,CT,860-331-1050,,monicaesten@gmail.com,ACCEPT,
-Nursing,NUR,Fernandes,Hailey,Belchertown,MA,413-345-8108,,haileyfer66@gmail.com,ACCEPT,
-Nursing,NUR,Fernandes,Joanna,Brockton,MA,508-216-4902,,joannafernandes1012@gmail.com,ACCEPT,
-Nursing,NUR,Fils,Danielle,Brockton,MA,588-369-7530,,dfils1901@gmail.com,ACCEPT,
-Nursing,NUR,Fisher,Jahnae,Springfield,MA,413-355-9685,,jahnaef32@gmail.com,ACCEPT,
-Nursing,NUR,Floser,Taylor,Millbury,MA,774-276-7773,,tfloser@nda-worc.org,DEPOSIT,YES
-Nursing,NUR,Foley,Maeve,Old Saybrook,CT,860-304-8145,,maevefoley17@gmail.com,ACCEPT,
-Nursing,NUR,Gagne,Hayleigh,Belchertown,MA,413-626-4146,413-813-4123,hayleigh.gagnee@gmail.com,DEPOSIT,YES
-Nursing,NUR,Gallant,Andre,Springfield,MA,413-275-5197,413-244-0290,102193@cpsge.org,ACCEPT,
-Nursing,NUR,Garutti,Madison,Ware,MA,413-544-8268,,madisongarutti@yahoo.com,ACCEPT,
-Nursing,NUR,Gay,Emily,Belchertown,MA,413-977-9491,,egay0524@gmail.com,DEPOSIT,YES
-Nursing,NUR,Girard,MacKenzie,East Longmeadow,MA,413-454-8184,,mackenzie.girard@eastlongmeadowma.gov,DEPOSIT,
-Nursing,NUR,Girouard,Ashley,Chicopee,MA,413-887-9714,413-519-2968,ashleygirouard0@gmail.com,ACCEPT,YES
-Nursing,NUR,Gomez Pastor,Ashby,Worcester,MA,774-312-4637,508-414-4122,student.126984@worcesterschools.net,ACCEPT,
-Nursing,NUR,Goncalves,Samantha,Ludlow,MA,413-519-3376,,stu0702.sgoncalves@ludlowps.org,DEPOSIT,YES
-Nursing,NUR,Gonzalez Matos,Jesus,Florence,MA,413-270-0522,,jesus.gonzalezmatos@stu.northampton-k12.us,ACCEPT,YES
-Nursing,NUR,Goodnow,Abigail,Williamsburg,MA,413-207-5161,,19goodnowabi@student.hr-k12.org,DEPOSIT,YES
-Nursing,NUR,Gowdy,Maria,Mashpee,MA,781-985-9563,,maria.a.p.gowdy16@gmail.com,ACCEPT,
-Nursing,NUR,Granado,Julia,Longmeadow,MA,413-313-2425,,julia5454@icloud.com,DEPOSIT,YES
-Nursing,NUR,Guay,Victoria,Chicopee,MA,413-575-2186,,victoriaaguay@gmail.com,DEPOSIT,YES
-Nursing,NUR,Guijarro-Sines,Sara,New London,CT,860-910-6690,,sguijarrosines@gmail.com,DEPOSIT,YES
-Nursing,NUR,Harrigan,Rhea,Hampden,MA,413-244-3383,,rheamac33@gmail.com,ACCEPT,
-Nursing,NUR,Heath,Megan,Westfield,MA,413-563-2568,,megpheath@gmail.com,ACCEPT,YES
-Nursing,NUR,Hoffman,Isabella,North Easton,MA,508-254-7291,,isabellanoelle.hoffman@gmail.com,DEPOSIT,YES
-Nursing,NUR,Hunter,Cecilia,Willimantic,CT,860-759-7603,,hunter.cecilia01@gmail.com,ACCEPT,
-Nursing,NUR,Ivanov,David,Westfield,MA,413-977-9873,,davidiuana97@gmail.com,DEPOSIT,
-Nursing,NUR,Jones,Katelyn,Spring Valley,CA,619-850-9957,,katie17jones@gmail.com,ACCEPT,
-Nursing,NUR,Kaletin,Natalya,Chicopee,MA,413-426-6598,,natalyakaletin@gmail.com,DEPOSIT,
-Nursing,NUR,Kelton,Avery,Greenfield,MA,413-522-8424,,keltona@pvrsdk12.org,ACCEPT,
-Nursing,NUR,Kennedy,Alyssa,Milford,NH,603-554-0234,,akennedy@milfordk12.org,ACCEPT,
-Nursing,NUR,King,Meghan,Berkley,MA,774-226-0891,,19kingm@student.sbregional.org,ACCEPT,
-Nursing,NUR,Kirk,Caroline,Enfield,CT,860-805-1552,,kirkcaroline@yahoo.com,ACCEPT,
-Nursing,NUR,Kononchuk,Ruth,Westfield,MA,413-579-1505,,kononchukruth@gmail.com,ACCEPT,
-Nursing,NUR,Kononchuk,Vanessa,Westfield,MA,413-454-9547,,vanessakononchuk@yahoo.com,ACCEPT,
-Nursing,NUR,Krasinkiewicz,Emily,Belchertown,MA,413-406-4241,,emilykras13@gmail.com,DEPOSIT,YES
-Nursing,NUR,Lacaprucia,Gabriella,Chicopee,MA,413-427-8139,,87079@cpsge.org,ACCEPT,
-Nursing,NUR,Laflamme,Connor,Belchertown,MA,(1413) 658-4604,,connorlaflamme@gmail.com,DEPOSIT,YES
-Nursing,NUR,Landry,Samantha,Agawam,MA,413-478-5193,,slandry37@comcast.net,DEPOSIT,YES
-Nursing,NUR,Lannon,Rheanna,Hampden,MA,413-301-2592,413-304-0951,lannonrheanna@yahoo.com,DEPOSIT,YES
-Nursing,NUR,Lariviere,Megan,Ware,MA,413-505-9164,,lariviere.meg@yahoo.com,DEPOSIT,YES
-Nursing,NUR,Lavoie,Sarah,Hudson,NH,603-921-1477,,campsarah@comcast.net,ACCEPT,
-Nursing,NUR,Livingston,Brianna,Killingworth,CT,203-927-1774,,bri_living@yahoo.com,ACCEPT,
-Nursing,NUR,Manno,Ariella,Chicopee,MA,413-888-7508,,88431@cpsge.org,ACCEPT,
-Nursing,NUR,Marciniec,Alyssa,Palmer,MA,413-883-1049,,alyssamarciniec@gmail.com,ACCEPT,YES
-Nursing,NUR,Marques,Flavia,Chicopee,MA,413-310-5624,,flaviamarques2001@hotmail.com,DEPOSIT,YES
-Nursing,NUR,Marshall,Alisiana,Springfield,MA,413-355-8017,413-420-3667,alisicmar@gmail.com,ACCEPT,
-Nursing,NUR,Marty,Alaysha,Chicopee,MA,413-769-5493,,lay.marty@gmail.com,DEPOSIT,
-Nursing,NUR,Mathon,Margaret,Williston,VT,802-355-4240,,margaretmathon@cvsdvt.org,ACCEPT,YES
-Nursing,NUR,McClendon,Zaria,Springfield,MA,413-657-9153,413-219-2903,zariamcclendon01@gmail.com,ACCEPT,
-Nursing,NUR,McDonnell-Kularski,Lindsay,Ware,MA,413-544-5470,,lkularski@gmail.com,ACCEPT,
-Nursing,NUR,McGinnis,Madison,Enfield,CT,860-719-1278,,mmmaddy2001@gmail.com,ACCEPT,
-Nursing,NUR,McGrath,Hannah,Wethersfield,CT,860-559-4280,860-560-3178,mcgrathhannah@wethersfield.me,ACCEPT,
-Nursing,NUR,McLellan,Alexia,Terryville,CT,860-309-9040,,lexmclel19@gmail.com,ACCEPT,
-Nursing,NUR,Mihalak,Moira,South Hadley,MA,413-784-3292,,moira6776@gmail.com,ACCEPT,YES
-Nursing,NUR,Miller,Ashlee,San Diego,CA,619-519-5018,,ashlee.miller@futures.edu,ACCEPT,
-Nursing,NUR,Mojica,Ana,Springfield,MA,413-777-0378,,anavaleriamojica11@gmail.com,ACCEPT,
-Nursing,NUR,Moreno Saravia,Mariela,South Hadley,MA,413-336-3987,,morenomariela178@gmail.com,ACCEPT,
-Nursing,NUR,Mrozinski,Kevin,Chicopee,MA,413-234-0934,,kevmro2000@gmail.com,ACCEPT,
-Nursing,NUR,Musk,Faith,Westbrook,ME,603-854-3132,,muskf19@westbrook.k12.me.us,ACCEPT,
-Nursing,NUR,Mwangi,Lainey,Wilbraham,MA,413-885-8106,413-279-1224,laineymwangi@gmail.com,DEPOSIT,YES
-Nursing,NUR,Nguyen,Susan,Springfield,MA,413-328-4111,,gamersusanstyles@gmail.com,DEPOSIT,YES
-Nursing,NUR,Norris,Kylee,Worcester,MA,508-375-8540,508-926-8575,kyleenorris01@gmail.com,DEPOSIT,
-Nursing,NUR,Oatley,Kaitlyn,Warwick,RI,401-419-4241,401-265-4967,kaitlynoatley@gmail.com,ACCEPT,
-Nursing,NUR,Pacheco,Chynna,Indian Orchard,MA,413-726-4989,,pachecochynna@gmail.com,ACCEPT,YES
-Nursing,NUR,Papapietro,Ashley,Windsor Locks,CT,1-860-830-1544,,ashleypapapiero@yahoo.com,ACCEPT,
-Nursing,NUR,Pasquel,Kayla,North Attleboro,MA,774-254-1709,,kaylapasquel@gmail.com,DEPOSIT,
-Nursing,NUR,Patel,Ishanee,Berlin,CT,203-584-2354,,isha111p@gmail.com,ACCEPT,
-Nursing,NUR,Petlock,Karlie,West Springfield,MA,413-207-5676,,kpetlock@smithtec.org,ACCEPT,
-Nursing,NUR,Pierce,Grace,Barre,VT,802-249-5139,,19grapierc@u61.net,ACCEPT,
-Nursing,NUR,Pikul,Anna-Elise,Belchertown,MA,413-325-4737,,elisepikul1327@gmail.com,ACCEPT,
-Nursing,NUR,Price,Anna,Holyoke,MA,413-537-4189,,annaapricee@gmail.com,ACCEPT,
-Nursing,NUR,Quinn,Madison,Pittsfield,MA,413-281-9882,,madisonquinn1113@gmail.com,ACCEPT,YES
-Nursing,NUR,Rivera,Deviyana,Northampton,MA,413-230-1257,413-923-4278,deviyana.rivera@stu.northampton-k12.us,ACCEPT,
-Nursing,NUR,Rodriguez,Arianna,Springfield,MA,413-304-1148,413-504-3312,arijaelyn2001@gmail.com,ACCEPT,
-Nursing,NUR,Rodriguez,Jocelyn,Westfield,MA,413-335-2232,,jocelynr05@aol.com,DEPOSIT,YES
-Nursing,NUR,Rosado,Naomi,Meriden,CT,203-499-8040,,rosadonaomi1@gmail.com,ACCEPT,
-Nursing,NUR,Rotatori,Mia,Naugatuck,CT,203-228-0306,,miarotatori@gmail.com,DEPOSIT,YES
-Nursing,NUR,Russell,Jillian,Westfield,MA,413-378-3801,413-539-1171,jillybean4423@comcast.net,DEPOSIT,YES
-Nursing,NUR,Sacha,Michael,Pasadena,MD,443-848-3629,,msacha2334@gmail.com,ACCEPT,
-Nursing,NUR,Saint Paulin,Francesca,Amesbury,MA,781-632-8309,781-353-1119,st.paulin2001@gmail.com,ACCEPT,
-Nursing,NUR,Seroter,Madison,Worcester,MA,508-860-3952,774-386-6212,mseroter1203@gmail.com,ACCEPT,
-Nursing,NUR,Serrao,Kellie,Chicopee,MA,413-657-8216,,kellieann2019@gmail.com,DEPOSIT,YES
-Nursing,NUR,Shaw,Olivia,Brockton,MA,508-577-8368,,liv2too@gmail.com,ACCEPT,
-Nursing,NUR,Silva,Kaylie,Douglas,MA,508-244-2701,,kayliespc@gmail.com,ACCEPT,
-Nursing,NUR,Smiley,Sydney,Spring Lake,NC,910-978-1113,,sydrules73@gmail.com,DEPOSIT,YES
-Nursing,NUR,Smith,Ashley,Lincoln,RI,401-603-9290,,LincolnAsh2001@cox.net,ACCEPT,
-Nursing,NUR,Soter,Kylie,Spencer,MA,508-269-9216,,kesoter@gmail.com,ACCEPT,YES
-Nursing,NUR,Souza,Laurana,Somerset,MA,508-536-1876,,lps62601@gmail.com,ACCEPT,
-Nursing,NUR,Steglitz,Mary,Thompson,CT,860-377-3275,774-289-2889,msteglitz2019@thompsonk12.org,ACCEPT,
-Nursing,NUR,Steward,Mary,Saco,ME,207-590-6157,207-809-0530,mary.steward19@thorntonacademy.org,ACCEPT,
-Nursing,NUR,Stringer,Hannah,Pittsfield,MA,413-441-0983,,hannah.stringer@bartcharter.org,ACCEPT,
-Nursing,NUR,Strout,Amanda,Springfield,MA,413-219-0437,,amandas12@icloud.com,DEPOSIT,
-Nursing,NUR,Sweeney,Cassidy,Westfield,MA,413-335-7529,,cassidymsweeney@comcast.net,DEPOSIT,YES
-Nursing,NUR,Szarkowski,Alexander,Belchertown,MA,413-885-0509,413-885-0231,alexszark@gmail.com,ACCEPT,YES
-Nursing,NUR,Tardiff,Grace,Turner,ME,207-356-8865,207-341-0214,graceellennnt@gmail.com,ACCEPT,
-Nursing,NUR,Theriault,Skyanne,Worcester,MA,508-864-6027,,skytheriault@gmail.com,ACCEPT,
-Nursing,NUR,Thomaz,Anna Clara,Lynn,MA,781-813-9465,,anna.thomaz67@gmail.com,ACCEPT,
-Nursing,NUR,Thompson,Nikeila,New London,CT,860-701-8948,,nikeilathompson2001@gmail.com,ACCEPT,
-Nursing,NUR,Tran,Mindy,Springfield,MA,413-356-0863,,mindytran561@gmail.com,ACCEPT,
-Nursing,NUR,Usataya,Ekaterina,Russell,MA,413-304-0596,,ekaterinausataya2000@gmail.com,ACCEPT,
-Nursing,NUR,Van Magness,Carrie,Reading,MA,781-439-3954,,carrieannvan17@gmail.com,DEPOSIT,YES
-Nursing,NUR,Vilar,Elaina,Watertown,CT,203-592-5528,,vilarem01@aol.com,DEPOSIT,YES
-Nursing,NUR,Villegas,Mikayla,Holyoke,MA,413-539-1799,,mikaylav0834@holyokestudents.org,ACCEPT,YES
-Nursing,NUR,Vorobey,Yana,Feeding Hills,MA,413-563-9298,413-209-4011,vorobeyyana@gmail.com,DEPOSIT,YES
-Nursing,NUR,Williams,Vannessa,Springfield,MA,413-404-6211,,vannessanw@gmail.com,ACCEPT,YES
-Nursing,NUR,Wilson,Katherine,Lanesboro,MA,413-449-6668,,katherinewilson2001@gmail.com,ACCEPT,
-Nursing,NUR,Wint,Jade,Brockton,MA,508-468-8980,,jadewint2019@gmail.com,ACCEPT,
-Nursing,NUR,Wolanski,Sara,Chicopee,MA,413-386-1515,,saraiw65@gmail.com,ACCEPT,
-Nursing,NUR,Wright,Cheyenne,Gilford,NH,603-455-3931,,cheyenne_wright@bishopbrady.edu,ACCEPT,
-Nursing,NUR,Zampiceni,Dominic,Agawam,MA,413-579-4988,,domzampiceni@gmail.com,ACCEPT,
diff --git a/_sources/Unit5-Writing-Classes/community-challenge.rst b/_sources/Unit5-Writing-Classes/community-challenge.rst
new file mode 100644
index 000000000..2654dc1b0
--- /dev/null
+++ b/_sources/Unit5-Writing-Classes/community-challenge.rst
@@ -0,0 +1,229 @@
+.. include:: ../common.rst
+
+|Time90|
+
+|Groupwork| Design a Class for your Community Project
+----------------------------------------------------------
+
+.. |worksheet| raw:: html
+
+ worksheet
+
+.. |tutorial on class diagrams| raw:: html
+
+ tutorial on class diagrams
+
+.. |Creately.com| raw:: html
+
+ Creately.com
+
+.. |app diagrams| raw:: html
+
+ app.diagrams.net
+
+In lessons 5.1, 5.2, and 5.6, you were asked to design a class of your own choice
+that is relevant to your community. If you would like to do this activity as 1 lab project rather than a piece at a time at the end of each lesson, you can create your complete class here. Or you may choose to create a different class of your own here.
+You can work in pairs on this project.
+
+1. Make your own copy of this |worksheet| from the File menu. For question 1, brainstorm and ask people in your community what would be important or useful for them to track in a community organization or activity or to help your community. For example, you could create a Java class to keep track of community events, club activities, athletic games or statistics, community leaders, performers or performances, health tracking, or another subject of your choice.
+
+2. Come up with your class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing). Come up with at least 3 instance variables that are attributes of things in that class. Think about what data type each variable should be. You can use the |worksheet| to design your class. Optionally, you may want to draw a UML class diagram for your class on paper or using |app diagrams| or |Creately.com| (see |tutorial on class diagrams|).
+
+
+Code your Class
+=================
+
+1. Create your class and its instance variables below.
+
+2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters.
+
+3. Write a print() method that uses System.out.println to print out all the instance variables.
+
+4. Create accessor (get) methods for each of the instance variables.
+
+5. Create mutator (set) methods for each of the instance variables.
+
+6. Create a ``toString`` method that returns all the information in the instance variables.
+
+7. Write an additional method for your class that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, e.g. print(format) could print the data according to an argument that is "plain" or "table" where the data is printed in a table drawn with dashes and lines (|).
+
+8. Write a main method that constructs at least 2 objects of your class using the constructor and then calls all of the methods that you created above to test them.
+
+
+.. activecode:: community-challenge-complete-project
+ :language: java
+ :autograde: unittest
+
+ Design your class for your community below.
+ ~~~~
+ public class // Add your class name here!
+ {
+ // 1. write 3 instance variables for class: private type variableName;
+
+ // 2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters.
+
+ // 3. Write a print() method that uses System.out.println to print out all the instance variables.
+
+ // 4. Create accessor (get) methods for each of the instance variables.
+
+ // 5. Create mutator (set) methods for each of the instance variables.
+
+ // 6. Create a toString() method that returns all the information in the instance variables.
+
+ // 7. Write an additional method for your class that takes a parameter.
+ // For example, there could be a print method with arguments that indicate how you want to print out
+ // the information, e.g. print(format) could print the data according to an argument that is "plain"
+ // or "table" where the data is printed in a table drawn with dashes and lines (|).
+
+ // 8. Write a main method that constructs at least 2 objects of your class
+ // using the constructor and then calls all of the methods that you created above to test them.
+ public static void main(String[] args)
+ {
+ // Construct 2 objects of your class using the constructor with different values
+
+
+ // call all of the objects methods to test them
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "3 Private";
+ String output = testPrivateInstanceVariables();
+ boolean passed = false;
+ if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1)))
+ passed = true;
+ passed = getResults(expect, output, "Checking private instance variable(s)", passed);
+ assertTrue(passed);
+ }
+
+ /* No longer required
+ @Test
+ public void testDefaultConstructor()
+ {
+ String output = checkDefaultConstructor();
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking default constructor");
+ assertTrue(passed);
+ } */
+
+ @Test
+ public void testConstructor3()
+ {
+ String output = checkConstructor(3);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking constructor with 3 parameters");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrint()
+ {
+ String output = getMethodOutput("print");
+ String expect = "More than 15 characters";
+ String actual = " than 15 characters";
+
+ if (output.length() < 15)
+ {
+ actual = "Less" + actual;
+ }
+ else
+ {
+ actual = "More" + actual;
+ }
+ boolean passed = getResults(expect, actual, "Checking print method");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main"); // .split("\n");
+ String expect = "3+ line(s) of text";
+ String actual = " line(s) of text";
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 3;
+
+ getResults(expect, actual, "Checking output", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ String target = "public * get*()";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 3;
+
+ getResults("3", "" + num, "Checking accessor (get) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "public void set*(*)";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 3;
+
+ getResults("3", "" + num, "Checking mutator (set) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "public String toString()";
+ boolean passed = checkCodeContains("toString() method", target);
+ assertTrue(passed);
+ }
+ }
+
+You will continue this project in Unit 6 in lessons 6.1-6.3 to create an array of objects using your class.
+
+
+Optional Swing GUI
+=====================
+
+.. |Java Swing Example| raw:: html
+
+ Java Swing Example
+
+An optional additional project is to build a GUI (graphical user interface) for your class (GUIs are not on the AP exam).
+Here's a |Java Swing Example| on repl and below that sets up a JFrame with JTextfields, JLabels, and a JButton.
+It calls a special method called addActionListener where you can put the code to be executed
+when you click on the button. This program prints out the entered data into a file, although more advanced systems would use a database.
+You can fork this project in replit or copy the code to your local computer to design
+an input form for your class. You can uncomment the code in the actionlistener that prints the entered data into a file.
+To learn more about Java Swing, click on the different Swing components in the left navigation column of https://www.javatpoint.com/java-swing.
+
+.. raw:: html
+
+
diff --git a/_sources/Unit5-Writing-Classes/midterm_unit5.rst b/_sources/Unit5-Writing-Classes/midterm_unit5.rst
new file mode 100644
index 000000000..7e1caf75f
--- /dev/null
+++ b/_sources/Unit5-Writing-Classes/midterm_unit5.rst
@@ -0,0 +1,654 @@
+.. qnum::
+ :prefix: 5-15-
+ :start: 1
+
+Midterm Test
+--------------
+
+The following 20 questions are similar to what you might see on the AP CSA exam for Units 1 - 5. You may only take this test once while logged in. There are no time limits, but it will keep track of how much time you take. Click on the finish button after you have answered all the questions, and the number correct and feedback on the answers will be displayed.
+
+We estimate that a score of about 50% on this test would correspond to the passing grade of 3 on the AP exam, a score of 65% to a 4, and a score of 80% and above to a 5 on the AP exam. These are just estimates and may not correspond to individual scores.
+
+
+.. timed:: midterm-exam-in-unit-5
+
+ .. mchoice:: mid_1_1
+ :answer_a: I only
+ :answer_b: I and II only
+ :answer_c: III only
+ :answer_d: IV and V only
+ :answer_e: V only
+ :correct: a
+ :feedback_a: Correct! This will loop with i changing from 1 to 5 and then for each i, j will loop from i to 0 printing the value of i and then a new line.
+ :feedback_b: II will loop i from 0 to 4 and j from 0 to i, neglecting to ouput 5.
+ :feedback_c: III will loop with i changing from 1 to 4 and j from i to 0.
+ :feedback_d: IV will loop with i changing from 1 to 5 and j from 0 to i but it will print each value on a different line.
+ :feedback_e: V will loop with i changing from 0 to 4 and j from 0 to i.
+
+ Which of the following code segments will produce the displayed output?
+
+ .. code-block:: java
+
+ /* Output:
+ 1
+ 22
+ 333
+ 4444
+ 55555
+ */
+
+ //Loop I
+ for (int i = 1; i <= 5; i++)
+ {
+ for (int j = i; j > 0; j--)
+ {
+ System.out.print(i);
+ }
+ System.out.println();
+ }
+
+ //Loop II
+ for (int i = 0; i < 5; i++)
+ {
+ for (int j = 0; j < i; j++)
+ {
+ System.out.print(i);
+ }
+ System.out.println();
+ }
+
+ //Loop III
+ for (int i = 1; i < 5; i++)
+ {
+ for (int j = i; j > 0; j--)
+ {
+ System.out.print(i);
+ }
+ System.out.println();
+ }
+
+ //Loop IV
+ for (int i = 1; i < 6; i++)
+ {
+ for (int j = 0; j < i; j++)
+ {
+ System.out.println(i);
+ }
+ }
+
+ //Loop V
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < i; j++) {
+ System.out.print(i+1);
+ }
+ System.out.println();
+ }
+
+
+
+ .. mchoice:: mid_1_2
+ :answer_a: A
+ :answer_b: AC
+ :answer_c: C
+ :answer_d: BD
+ :answer_e: E
+ :correct: c
+ :feedback_a: num2 is negative
+ :feedback_b: Only one letter will be printed.
+ :feedback_c: Correct because num2 is negative and an or is used.
+ :feedback_d: Only one letter will be printed.
+ :feedback_e: One of the other conditions is true.
+
+ Consider the following method. What is the output from ``conditionTest(3,-2);``?
+
+ .. code-block:: java
+
+ public static void conditionTest(int num1, int num2)
+ {
+ if ((num1 > 0) && (num2 > 0))
+ {
+ if (num1 > num2)
+ System.out.println("A");
+ else
+ System.out.println("B");
+ }
+ else if ((num2 < 0) || (num1 < 0))
+ {
+ System.out.println("C");
+ }
+ else if (num2 < 0)
+ {
+ System.out.println("D");
+ }
+ else
+ {
+ System.out.println("E");
+ }
+ }
+
+ .. mchoice:: mid_1_3
+ :answer_a: I only
+ :answer_b: II only
+ :answer_c: II and III only
+ :answer_d: I and II only
+ :answer_e: I, II, and III
+ :correct: d
+ :feedback_a: Loop I will produce this output, but it is not the only loop that will output these values.
+ :feedback_b: Loop II will produce this output, but it is not the only loop that will output these values.
+ :feedback_c: Loop II is correct, but loop III will produce the reverse output, 43210.
+ :feedback_d: Correct! Both of these loops will produce the correct output.
+ :feedback_e: While loop I and II will produce the correct output, loop III will actually produce the reverse of the correct output.
+
+ Which of these loops will output ``01234``?
+
+ .. code-block:: java
+
+ int max = 5;
+
+ //Loop I
+ for (int i = 0; i < max; i++)
+ {
+ System.out.print(i);
+ }
+
+ //Loop II
+ int j = 0;
+ while (j < max)
+ {
+ System.out.print(j);
+ j++;
+ }
+
+ //Loop III
+ int k = 0;
+ for (int i = max; i > 0; i--)
+ {
+ System.out.print(i);
+ }
+
+ .. mchoice:: mid_1_4
+ :answer_a: 25
+ :answer_b: 15
+ :answer_c: 125
+ :answer_d: 64
+ :answer_e: 625
+ :correct: c
+ :feedback_a: This would be the correct answer if there were only two loops nested, but there are three. Try again!
+ :feedback_b: Take a look at how many times each inner loop will execute every time the outer loop runs.
+ :feedback_c: Correct!
+ :feedback_d: Try again - check the difference between <= and < in each loop.
+ :feedback_e: If you got this value you probably made one extra call to the each of the loops, notice that the loops start at 1 and not 0.
+
+ Consider the following block of code. What value is returned from ``solution(5)``?
+
+ .. code-block:: java
+
+ public int solution(int limit)
+ {
+ int s = 0;
+ for (int outside = 1; outside <= limit; outside++)
+ {
+ for (int middle = 1; middle <= limit; middle++)
+ {
+ for (int inside = 1; inside <= limit; inside++)
+ {
+ s++;
+ }
+ }
+ }
+ return s;
+ }
+
+ .. mchoice:: mid_1_5
+ :answer_a: (x < 10) && (x > 5)
+ :answer_b: (x > 10) && (x <=5)
+ :answer_c: (x <= 10) && (x > 5)
+ :answer_d: (x <= 10) || (x > 5)
+ :answer_e: (x > 10) || (x <= 5)
+ :correct: d
+ :feedback_a: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (!A && !B).
+ :feedback_b: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (A && B).
+ :feedback_c: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (!A && !B). The AND should be changed to an OR.
+ :feedback_d: Correct!
+ :feedback_e: Use A and B to represent the expressions -- A becomes (x > 10), B becomes (x <= 5). ! (A && B) is NOT equivalent to (A || B). Both A and B should also be negated.
+
+ Which of the following is equivalent to !((x > 10) && (x <= 5)) ?
+
+ .. mchoice:: mid_1_6
+ :answer_a: s="rainbow"; b=8;
+ :answer_b: s="rain"; b=8;
+ :answer_c: s="rainbow"; b=4;
+ :answer_d: s="rain"; b=4;
+ :answer_e: s="bow"; b=4;
+ :correct: d
+ :feedback_a: Strings are immutable so changing str doesn't affect the string that s refers to.
+ :feedback_b: Nothing done in the method test affects the value of b.
+ :feedback_c: Strings are immutable so changing str doesn't affect the string that s refers to.
+ :feedback_d: Correct!
+ :feedback_e: All changes to string s result in a new string object.
+
+
+ Consider the following class with the method ``test``. What is the output after the main method is executed calling ``test(s,b)``?
+
+ .. code-block:: java
+
+ public class Test1
+ {
+ public static void test(String str, int y)
+ {
+ str = str + "bow";
+ y = y * 2;
+ }
+
+ public static void main(String[] args)
+ {
+ String s = "rain";
+ int b = 4;
+ test(s, b);
+ System.out.println("s=" + s + "; b=" + b);
+ }
+ }
+
+ .. mchoice:: mid_1_7
+ :answer_a: The ``getAge()`` method should be declared as private.
+ :answer_b: The return type of the ``getAge()`` method should be void.
+ :answer_c: The ``getAge()`` method should have at least one parameter.
+ :answer_d: The variable ``age`` is not declared inside the ``getAge()`` method.
+ :answer_e: The instance variable ``age`` should be returned instead of a, which is local to the constructor.
+ :correct: e
+ :feedback_a: The method should be public so it can be accessed outside of the class.
+ :feedback_b: The method's return type should be int.
+ :feedback_c: The getAge method should not take any parameters.
+ :feedback_d: This is an instance variable and should be declared outside of the method.
+ :feedback_e: Correct! The accessor method getAge should return the instance variable age.
+
+ Consider the following ``Cat`` class that has an ``age`` attribute of type int. The ``getAge`` method is intended to allow methods in other classes to access a Cat object’s age value; however, it does not work as intended. Which of the following best explains why the ``getAge`` method does NOT work as intended?
+
+ .. code-block:: java
+
+ public class Cat
+ {
+ private int age;
+
+ public Cat(int a)
+ {
+ age = a;
+ }
+
+ public int getAge()
+ {
+ return a;
+ }
+ }
+
+ .. mchoice:: mid_1_8
+ :answer_a: I only
+ :answer_b: I and II only
+ :answer_c: I and III only
+ :answer_d: I, II, and III
+ :answer_e: II and III only
+ :correct: d
+ :feedback_a: It's true that the local variables can be declared in the body of constructors and methods, but there are other options that are also true about local variables.
+ :feedback_b: Both I and II are true but III is also true regarding local variables.
+ :feedback_c: Both I and III are true but II is also true regarding local variables.
+ :feedback_d: Correct! All of the above are true.
+ :feedback_e: Both of these are true but I is also true.
+
+ Which of the following statements are TRUE about local variables?
+
+ I. Local variables can be declared in the body of constructors and methods.
+
+ II. Local variables may only be used within the constructor or method and cannot be declared to be public or private.
+
+ III. When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable.
+
+
+ .. mchoice:: mid_1_9
+ :answer_a: I and II only
+ :answer_b: I, II, and III
+ :answer_c: I and III only
+ :answer_d: I only
+ :answer_e: III only
+ :correct: c
+ :feedback_a: Static methods cannot acccess instance variables. They can only access static variables.
+ :feedback_b: Static methods cannot acccess instance variables. They can only access static variables.
+ :feedback_c: Correct! I and III are true, but static methods cannot acccess instance variables. They can only access static variables.
+ :feedback_d: I is true, but there is another option that is true too.
+ :feedback_e: III is true, but there is another option that is true too.
+
+ Which of the following statements are TRUE about **static** methods?
+
+ I. Static methods and variables include the keyword static before their name in the header or declaration and can be public or private.
+
+ II. Static methods can access or change the values of instance variables.
+
+ III. Static methods are associated with the class, not objects of the class.
+
+ .. mchoice:: mid_1_10
+ :answer_a: var1 = 0, var2 = 2
+ :answer_b: var1 = 1, var2 = 1
+ :answer_c: var1 = 3, var2 = -1
+ :answer_d: var1 = 2, var2 = 0
+ :answer_e: The loop won't finish executing because of a division by zero.
+ :correct: d
+ :feedback_a: This would be true if the body of the while loop never executed. This would have happened if the while check was if var1 != 0 instead of var2 != 0
+ :feedback_b: This would be true if the body of the while loop only execued one time, but it executes twice.
+ :feedback_c: This would be true if the body of the while loop executed three times, but it executes twice.
+ :feedback_d: Correct!
+ :feedback_e: 0/2 won't cause a division by zero. The result is just zero.
+
+ What are the values of ``var1`` and ``var2`` after the following code segment is executed and the while loop finishes?
+
+ .. code-block:: java
+
+ int var1 = 0;
+ int var2 = 2;
+ while ((var2 != 0) && ((var1 / var2) >= 0))
+ {
+ var1 = var1 + 1;
+ var2 = var2 - 1;
+ }
+
+ .. mchoice:: mid_1_11
+ :answer_a: 5 4 3 2 1
+ :answer_b: -5 -4 -3 -2 -1
+ :answer_c: -4 -3 -2 -1 0
+ :answer_d: -5 -4 -3 -2 -1 0
+ :answer_e: -4 -3 -2 -1
+ :correct: c
+ :feedback_a: x is initialized (set) to -5 to start and incremented (x++) before the print statement executes.
+ :feedback_b: x is incremented (x++) from -5 before the print statement executes.
+ :feedback_c: Correct!
+ :feedback_d: x is incremented (x++) from -5 before the print statement executes.
+ :feedback_e: 0 is printed out the last time through the loop when x is -1 and is incremented.
+
+ What does the following code print?
+
+ .. code-block:: java
+
+ int x = -5;
+ while (x < 0)
+ {
+ x++;
+ System.out.print(x + " ");
+ }
+
+ .. mchoice:: mid_1_12
+ :answer_a: 0 3 6 9 12
+ :answer_b: 0 1 2 3 4 5
+ :answer_c: 1 4 7 10 13
+ :answer_d: 0 3 6 9 12 15
+ :answer_e: This code will not print anything.
+ :correct: d
+ :feedback_a: It would also print 15.
+ :feedback_b: The conditional would only match multiples of three.
+ :feedback_c: The conditional would only match multiples of three.
+ :feedback_d: Yes, the multiples of 3 from 0 to 15.
+ :feedback_e: This code would print the multiples of 3.
+
+ What will be printed after this code is executed?
+
+ .. code-block:: java
+
+ for (int i = 0; i <= 15; i++)
+ {
+ if (i % 3 == 0)
+ {
+ System.out.print(i + " ");
+ }
+ }
+
+ .. mchoice:: mid_1_13
+ :answer_a: I only
+ :answer_b: II only
+ :answer_c: IV only
+ :answer_d: II and III
+ :answer_e: I, II, and III
+ :correct: d
+ :feedback_a: This implementation of ``addMinutes`` does not account for values of additionMinutes that push the minute count above 60.
+ :feedback_b: Implementation II works, but implementation III also works.
+ :feedback_c: Implementation IV does not work for situations where additionMinutes + minutes does not go above 60.
+ :feedback_d: Correct!
+ :feedback_e: Implementations II and III are correct, but implementation I is not. Implementation I does not account for values of additionMinutes that push the minute account above 60.
+
+ Consider the following declaration for a class that will be used to represent points in time. Which of these options correctly implement ``addMinutes()``?
+
+ .. code-block:: java
+
+ public class Timer
+ {
+ private int hours; // number of hours
+ private int minutes; // 0 <= minutes < 60
+
+ void addHours(int addition)
+ {
+ hours = hours + addition;
+ }
+
+ /** addMinutes adds the given argument to the time stored in hours and minutes.
+ The argument additionMinutes is between 0 and 119. **/
+ void addMinutes(int additionMinutes)
+ {
+ // implementation not shown
+ }
+
+ // ... other methods not shown
+ }
+
+
+ //Proposed Implementations:
+ I. public void addMinutes(int additionMinutes)
+ {
+ minutes = minutes + additionMinutes;
+ }
+ II. public void addMinutes(int additionMinutes)
+ {
+ minutes += additionMinutes;
+ if (minutes >= 60)
+ {
+ hours += minutes / 60;
+ minutes = minutes % 60;
+ }
+ }
+ III. public void addMinutes(int additionMinutes)
+ {
+ minutes += additionMinutes;
+ while (minutes >= 60)
+ {
+ hours++;
+ minutes -= 60;
+ }
+ }
+ IV. public void addMinutes(int additionMinutes)
+ {
+ if (additionMinutes + minutes >= 60)
+ {
+ minutes = additionMinutes + minutes - 60;
+ hours += 1;
+ }
+ }
+
+ .. mchoice:: mid_1_14
+ :answer_a: !(a && b)
+ :answer_b: !a && b
+ :answer_c: !a && !b
+ :answer_d: a && b
+ :answer_e: a || !b
+ :correct: c
+ :feedback_a: This would be true in any case where a and b weren't both true
+ :feedback_b: If b was false, this option would be false.
+ :feedback_c: Correct!
+ :feedback_d: This will only be true only when both a and b are true.
+ :feedback_e: This will only be true if a is true, or b is false.
+
+ Which option will evaluate to true, if and only if both a and b are false?
+
+ .. mchoice:: mid_1_15
+ :answer_a: Prints the string in reverse order
+ :answer_b: Deletes the second half of the string
+ :answer_c: Prints string normally
+ :answer_d: Compile-time error occurs
+ :answer_e: Prints alternating characters from beginning and end of the string.
+ :correct: a
+ :feedback_a: Correct! This method prints the reversed string.
+ :feedback_b: Incorrect, this method prints the parameter reversed.
+ :feedback_c: Incorrect, this method prints the parameter reversed.
+ :feedback_d: Incorrect, this method prints the parameter reversed.
+ :feedback_e: Incorrect, this method prints the parameter reversed.
+
+ What does the method ``mystery`` do?
+
+ .. code-block:: java
+
+ public void mystery(String tester)
+ {
+ for (int i = tester.length() - 1; i >= 0; i--)
+ {
+ System.out.print(tester.substring(i,i+1));
+ }
+ System.out.println("");
+ }
+
+ .. mchoice:: mid_1_16
+ :answer_a: "Hello World!"
+ :answer_b: "Hello "
+ :answer_c: "He"
+ :answer_d: "HloWrd"
+ :answer_e: "el ol!"
+ :correct: d
+ :feedback_a: The variable holds all characters that were stored at even indices for the original phrase.
+ :feedback_b: The variable holds all characters that were stored at even indices for the original phrase.
+ :feedback_c: The variable holds all characters that were stored at even indices for the original phrase.
+ :feedback_d: Correct! The variable holds all characters that were stored at even indices for the original phrase.
+ :feedback_e: The variable holds all characters that were stored at even indices for the original phrase.
+
+ After the following code is executed, what does the variable ``mystery`` hold?
+
+ .. code-block:: java
+
+ public class Mysterious
+ {
+ public static void main(String[] args)
+ {
+ String mystery = "";
+ String starter = "Hello World!";
+ for (int i = 0; i < starter.length(); i++)
+ {
+ if (i % 2 == 0)
+ {
+ mystery += starter.substring(i, i + 1);
+ }
+ }
+ }
+ }
+
+ .. mchoice:: mid_1_17
+ :answer_a: I only
+ :answer_b: I and II
+ :answer_c: II only
+ :answer_d: II and III
+ :answer_e: I, II, and III
+ :correct: c
+ :feedback_a: I contains incorrect syntax. Try again!
+ :feedback_b: I contains incorrect syntax. Try again!
+ :feedback_c: Correct! II is the only correct option.
+ :feedback_d: III is incorrect due to a problem with the constructor argument. Try again!
+ :feedback_e: Two of these options are incorrect. Take a closer look at the syntax of I and parameters of III.
+
+ Which of the following code segments correctly creates an instance of a new ``Party`` object?
+
+ .. code-block:: java
+
+ public class Party
+ {
+
+ private int numInvited;
+ private boolean partyCancelled;
+
+ public Party()
+ {
+ numInvited = 1;
+ partyCancelled = false;
+ }
+
+ public Party(int invites)
+ {
+ numInvited = invites;
+ partyCancelled = false;
+ }
+ }
+
+ I. Party myParty;
+ II. int classSize = 20;
+ Party ourParty = new Party(classSize);
+ III. int numOfFriends = 6;
+ Party yourParty = new Party(numOfFriends + 3.0);
+
+ .. mchoice:: mid_1_18
+ :answer_a: a = 6 and b = 7
+ :answer_b: a = 6 and b = 13
+ :answer_c: a = 13 and b = 0
+ :answer_d: a = 6 and b = 0
+ :answer_e: a = 0 and b = 13
+ :correct: c
+ :feedback_a: This would be true if the loop stopped when i was equal to 6. Try again!
+ :feedback_b: Take another look at how a and b change in each iteration of the loop.
+ :feedback_c: Correct!
+ :feedback_d: Almost there! b = 0, but take another look at how a changes in each iteration of the loop.
+ :feedback_e: Take another look at how a and b change within each iteration of the loop. You are close!
+
+ What are the values of ``a`` and ``b`` after the ``for`` loop finishes?
+
+ .. code-block:: java
+
+ int a = 10, b = 3, t = 0;
+ for (int i = 1; i <= 6; i++)
+ {
+ t = a;
+ a = i + b;
+ b = t - i;
+ }
+
+ .. mchoice:: mid_1_19
+ :answer_a: hi there
+ :answer_b: HI THERE
+ :answer_c: Hi There
+ :answer_d: null
+ :answer_e: hI tHERE
+ :correct: c
+ :feedback_a: Strings are immutable and so any change to a string returns a new string.
+ :feedback_b: Strings are immutable and so any change to a string returns a new string.
+ :feedback_c: Correct!
+ :feedback_d: Strings are immutable and so any changes to a string returns a new string.
+ :feedback_e: Strings are immutable and so any changes to a string returns a new string.
+
+ Consider the following code. What string is referenced by ``s1`` after the code executes?
+
+ .. code-block:: java
+
+ String s1 = "Hi There";
+ String s2 = s1;
+ String s3 = s2;
+ String s4 = s1;
+ s2 = s2.toLowerCase();
+ s3 = s3.toUpperCase();
+ s4 = null;
+
+ .. mchoice:: mid_1_20
+ :answer_a: a = 6.7
+ :answer_b: b = 87.7
+ :answer_c: 12 = c * b
+ :answer_d: c = a - b
+ :correct: d
+ :feedback_a: Check the data type of a.
+ :feedback_b: Check the data type of b.
+ :feedback_c: Assignment statements must have a variable on the left.
+ :feedback_d: Correct!
+
+ Given following code, which of the following statements is a valid assignment statement using these variables?
+
+ .. code-block:: java
+
+ int a = 5;
+ int b = 3;
+ int c = 4;
diff --git a/_sources/Unit5-Writing-Classes/timeFRQ.rst b/_sources/Unit5-Writing-Classes/timeFRQ.rst
index 8d4fd66ed..40e72bb40 100644
--- a/_sources/Unit5-Writing-Classes/timeFRQ.rst
+++ b/_sources/Unit5-Writing-Classes/timeFRQ.rst
@@ -1,14 +1,7 @@
-.. .. qnum::
- :prefix: 5-11-
- :start: 1
-
-.. highlight:: java
- :linenothreshold: 4
-
Free Response Question - Time
-------------------------------
-.. index::
+.. index::
single: time
single: free response
@@ -118,322 +111,357 @@ Use conditionals (if statements) to check for each of these conditions and take
.. activecode:: time_part_a
:language: java
- :autograde: unittest
+ :autograde: unittest
/**
- * Objects of the Time class hold a time value for
- * a European-style 24 hour clock.
- * The value consists of hours, minutes and seconds.
- * The range of the value is 00:00:00 (midnight)
- * to 23:59:59 (one second before midnight).
+ * 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;
- }
+ // 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;
- }
+ /**
+ * 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 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);
- }
+ 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;
- }
+ /**
+ * 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");
-
-
+ Time time = new Time(0, 0, 0);
+ time.tick();
+ System.out.println(
+ "For (0,0,0) and tick() you got "
+ + time
+ + " which should be 00:00:01");
+
+ time = new Time(0, 0, 58);
+ time.tick();
+ System.out.println(
+ "For (0,0,58) and tick() you got "
+ + time
+ + " which should be 00:00:59");
+
+ time = new Time(0, 0, 59);
+ time.tick();
+ System.out.println(
+ "For (0,0,59) and tick() you got "
+ + time
+ + " which should be 00:01:00");
+
+ time = new Time(0, 58, 59);
+ time.tick();
+ System.out.println(
+ "For (0,58,59) and tick() you got "
+ + time
+ + " which should be 00:59:00");
+
+ time = new Time(0, 59, 59);
+ time.tick();
+ System.out.println(
+ "For (0,59,59) and tick() you got "
+ + time
+ + " which should be 01:00:00");
+
+ time = new Time(23, 59, 59);
+ time.tick();
+ System.out.println(
+ "For (23,59,59) and tick() you got "
+ + time
+ + " which should be 00:00:00");
}
- }
+ }
+
====
// Test Code for Lesson 5.14 - FRQ - Time - Part A
+
import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
+
import org.junit.Test;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- private Time[] time = {new Time(0,0,0), new Time(0,0, 58), new Time(0,0, 59), new Time(0,58, 59), new Time(0,59, 59), new Time(23,59, 59)};
- private String[] expected = {"00:00:01", "00:00:59", "00:01:00", "00:59:00", "01:00:00", "00:00:00"};
+ private Time[] time =
+ {
+ new Time(0, 0, 0),
+ new Time(0, 0, 58),
+ new Time(0, 0, 59),
+ new Time(0, 58, 59),
+ new Time(0, 59, 59),
+ new Time(23, 59, 59)
+ };
+ private String[] expected =
+ {
+ "00:00:01", "00:00:59", "00:01:00", "00:59:00", "01:00:00", "00:00:00"
+ };
@Test
public void test0() throws IOException
{
Time time = new Time(0, 0, 0);
+ String label = time.toString() + ".tick()";
time.tick();
String actual = time.toString();
String expected = "00:00:01";
- boolean passed = getResults(expected, actual, time.toString() +".tick()");
+ boolean passed = getResults(expected, actual, label);
assertTrue(passed);
}
@Test
public void test1() throws IOException
{
- int i = 1;
+ int i = 1;
+ String label = time[i].toString() + ".tick()";
time[i].tick();
String actual = time[i].toString();
- boolean passed = getResults(expected[i], actual, time[i].toString() +".tick()");
+ boolean passed = getResults(expected[i], actual, label);
assertTrue(passed);
}
@Test
public void test2() throws IOException
{
- int i = 2;
+ int i = 2;
+ String label = time[i].toString() + ".tick()";
time[i].tick();
String actual = time[i].toString();
- boolean passed = getResults(expected[i], actual, time[i].toString() +".tick()");
+ boolean passed = getResults(expected[i], actual, label);
assertTrue(passed);
}
@Test
public void test3() throws IOException
{
- int i = 3;
+ int i = 3;
+ String label = time[i].toString() + ".tick()";
time[i].tick();
String actual = time[i].toString();
- boolean passed = getResults(expected[i], actual, time[i].toString() +".tick()");
+ boolean passed = getResults(expected[i], actual, label);
assertTrue(passed);
}
@Test
public void test4() throws IOException
{
- int i = 4;
+ int i = 4;
+ String label = time[i].toString() + ".tick()";
time[i].tick();
String actual = time[i].toString();
- boolean passed = getResults(expected[i], actual, time[i].toString() +".tick()");
+ boolean passed = getResults(expected[i], actual, label);
assertTrue(passed);
}
@Test
public void test5() throws IOException
{
- int i = 5;
+ int i = 5;
+ String label = time[i].toString() + ".tick()";
time[i].tick();
String actual = time[i].toString();
- boolean passed = getResults(expected[i], actual, time[i].toString() +".tick()");
+ boolean passed = getResults(expected[i], actual, label);
assertTrue(passed);
}
}
-
**Part b.** Write the method ``add(Time offset)`` which adds the seconds together and makes sure the result is 59 or less (incrementing the minutes as needed), adds the minutes together and makes sure the result is 59 or less (increments the hours as needed), and adds the hours together (resetting the hours to 0 if it reaches 24). When you have finished writing the method, click "Run" to test your solution. The main method has code that will test your solution using several different times.
.. activecode:: time_part_b
:language: java
- :autograde: unittest
+ :autograde: unittest
/**
- * Objects of the Time class hold a time value for
- * a European-style 24 hour clock.
- * The value consists of hours, minutes and seconds.
- * The range of the value is 00:00:00 (midnight)
- * to 23:59:59 (one * second before midnight).
+ * 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;
- }
+ // 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;
- }
+ /**
+ * 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)
- {
+ /**
+ * 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);
- }
+ 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;
- }
+ /**
+ * 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)");
-
-
-
+ Time time1 = new Time(1, 1, 1);
+ Time time2 = new Time(2, 2, 2);
+ time1.add(time2);
+ System.out.println(
+ "The result of (1,1,1).add(2,2,2) is "
+ + time1
+ + " and should be (03:03:03)");
+
+ time1 = new Time(0, 0, 59);
+ time2 = new Time(0, 0, 1);
+ time1.add(time2);
+ System.out.println(
+ "The result of (0,0,59).add(0,0,1) is "
+ + time1
+ + " and should be (00:01:00)");
+
+ time1 = new Time(0, 59, 0);
+ time2 = new Time(0, 0, 1);
+ time1.add(time2);
+ System.out.println(
+ "The result of (0,59,0).add(0,0,1) is "
+ + time1
+ + " and should be (00:59:01)");
+
+ time1 = new Time(0, 59, 59);
+ time2 = new Time(0, 0, 1);
+ time1.add(time2);
+ System.out.println(
+ "The result of (0,59,59).add(0,0,1) is "
+ + time1
+ + " and should be (01:00:00)");
+
+ time1 = new Time(23, 0, 0);
+ time2 = new Time(1, 0, 0);
+ time1.add(time2);
+ System.out.println(
+ "The result of (23,0,0).add(1,0,0) is "
+ + time1
+ + " and should be (00:00:00)");
+
+ time1 = new Time(23, 59, 59);
+ time2 = new Time(23, 59, 59);
+ time1.add(time2);
+ System.out.println(
+ "The result of (23,59,59).add(23,59,59) is "
+ + time1
+ + " and should be (23:59:58)");
}
- }
+ }
+
====
// Test Code for Lesson 5.14 - FRQ - Time - Part B
import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
+
import org.junit.Test;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
@@ -441,14 +469,14 @@ Use conditionals (if statements) to check for each of these conditions and take
@Test
public void test1() throws IOException
{
- Time time1 = new Time(1,1,1);
- Time time2 = new Time(2,2,2);
+ Time time1 = new Time(1, 1, 1);
+ Time time2 = new Time(2, 2, 2);
time1.add(time2);
String expected = "03:03:03";
String actual = time1.toString();
- String msg = time1.toString() +".add(" + time2.toString() + ")";
+ String msg = time1.toString() + ".add(" + time2.toString() + ")";
boolean passed = getResults(expected, actual, msg);
assertTrue(passed);
@@ -457,70 +485,76 @@ Use conditionals (if statements) to check for each of these conditions and take
@Test
public void test2() throws IOException
{
- Time time1 = new Time(0,0,59);
- Time time2 = new Time(0,0,1);
+ Time time1 = new Time(0, 0, 59);
+ Time time2 = new Time(0, 0, 1);
time1.add(time2);
String expected = "00:01:00";
String actual = time1.toString();
- boolean passed = getResults(expected, actual, time1.toString() +".add(" + time2.toString() + ")");
+ boolean passed =
+ getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")");
assertTrue(passed);
}
@Test
public void test3() throws IOException
{
- Time time1 = new Time(0,59,0);
- Time time2 = new Time(0,0,1);
+ Time time1 = new Time(0, 59, 0);
+ Time time2 = new Time(0, 0, 1);
time1.add(time2);
String expected = "00:59:01";
String actual = time1.toString();
- boolean passed = getResults(expected, actual, time1.toString() +".add(" + time2.toString() + ")");
+ boolean passed =
+ getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")");
assertTrue(passed);
}
@Test
public void test4() throws IOException
{
- Time time1 = new Time(0,59,59);
- Time time2 = new Time(0,0,1);
+ Time time1 = new Time(0, 59, 59);
+ Time time2 = new Time(0, 0, 1);
time1.add(time2);
String expected = "01:00:00";
String actual = time1.toString();
- boolean passed = getResults(expected, actual, time1.toString() +".add(" + time2.toString() + ")");
+ boolean passed =
+ getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")");
assertTrue(passed);
}
@Test
public void test5() throws IOException
{
- Time time1 = new Time(23,0,0);
- Time time2 = new Time(1,0,0);
+ Time time1 = new Time(23, 0, 0);
+ Time time2 = new Time(1, 0, 0);
time1.add(time2);
String expected = "00:00:00";
String actual = time1.toString();
- boolean passed = getResults(expected, actual, time1.toString() +".add(" + time2.toString() + ")");
+ boolean passed =
+ getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")");
assertTrue(passed);
}
@Test
public void test6() throws IOException
{
- Time time1 = new Time(23,59,59);
- Time time2 = new Time(23,59,59);
+ Time time1 = new Time(23, 59, 59);
+ Time time2 = new Time(23, 59, 59);
time1.add(time2);
String expected = "23:59:58";
String actual = time1.toString();
- boolean passed = getResults(expected, actual, time1.toString() +".add(" + time2.toString() + ")");
+ boolean passed =
+ getResults(expected, actual, time1.toString() + ".add(" + time2.toString() + ")");
assertTrue(passed);
}
}
+
diff --git a/_sources/Unit5-Writing-Classes/toctree.rst b/_sources/Unit5-Writing-Classes/toctree.rst
index f80c7a952..3c4e7a5a9 100644
--- a/_sources/Unit5-Writing-Classes/toctree.rst
+++ b/_sources/Unit5-Writing-Classes/toctree.rst
@@ -1,19 +1,19 @@
.. image:: ../../_static/CSAwesomeLogo.png
:width: 350
:align: center
-
+
Writing Classes
:::::::::::::::
-
+
Class Periods: 12-14
-AP CS A Exam Weighting: 5-7.5%
+AP CSA Exam Weighting: 5-7.5%
.. toctree::
:maxdepth: 3
-
+
topic-5-1-parts-of-class.rst
topic-5-2-writing-constructors.rst
topic-5-3-comments-conditions.rst
@@ -25,17 +25,13 @@ AP CS A Exam Weighting: 5-7.5%
topic-5-9-this.rst
topic-5-10-social-impacts.rst
topic-5-11-summary.rst
+ topic-parsons-practice.rst
+ topic-toggle-problems.rst
Exercises.rst
+ midterm_unit5.rst
FRQstepTracker.rst
timeFRQ.rst
APLine.rst
CBLabs.rst
-
-
-.. Incorporate things from: firstOOClass.rst
- runClass.rst
- JavaBasicsSummary.rst
- objectObasics.rst
- objects&Classes.rst
-
-
\ No newline at end of file
+ community-challenge.rst
+
diff --git a/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst b/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst
index 9f2c974cc..929bedcd6 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-1-parts-of-class.rst
@@ -1,167 +1,250 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-1-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+|Time90|
Anatomy of a Java Class
=======================
-In Unit 2, we learned to use **classes** and **objects** that are built-in to Java or written by other programmers. In this unit, you will learn to write your own classes and objects!
-
-Creating a Class
-------------------
-
-Remember that a **class** in programming defines a new **abstract data type**. When you create **objects**, you create new variables or **instances** of that class data type. For example in Unit 2, we created yertle and myrtle, 2 turtle objects created from the class Turtle, and we used the Java String class to create different String variables, also called **object references**.
+In Unit 2, we learned to use **classes** and **objects** that are built-in to
+Java or written by other programmers. In this unit, you will learn to write your
+own classes and make your own objects!
-.. |video| raw:: html
+Remember that a **class** in Java defines a blueprint for creating objects. When
+you create **objects**, you create new **instances** of that class and what you
+can do with those instances is determined by what methods are defined in the
+class.
- video
+For example in Unit 2, we created ``yertle`` and ``myrtle``, 2 ``Turtle``
+variables and assigned them references to objects created from the class
+``Turtle`` and we used instances of Java’s ``String`` class to assign values to
+different ``String`` variables.
+Watch this short video to review the vocabulary of object-oriented programming:
-Here is a fun |video| demonstrating the difference between the class House which is a blueprint of a house and the objects which are individual houses built from that blueprint. You can't live on a blueprint although it describes a house! But you can use it to build houses and live in those. You can think of a class as like a blueprint or a cookie cutter or a factory that produces objects.
-
+.. youtube:: LfSaSANJPLg
+ :width: 650
+ :height: 415
+ :align: center
-.. youtube:: 1JJL0YszYik
- :height: 315
- :width: 560
- :align: left
+Creating a Class
+------------------
+Most classes you write will have the keyword ``public`` before them though it is
+not required. The class definition itself always starts with the word ``class``
+followed by the name of the class. Then the rest of the class, called the body,
+is defined inside a pair of ``{}``\ s.
-To write your own class, you typically start a class declaration with ``public`` then ``class`` then the name of the class. The body of the class is defined inside a ``{`` and a ``}``. For example, the class House below. Then, you can create objects of that new House type by using ``Classname objectname = new Classname();``
+Since we’re talking about anatomy, let’s create a class called ``Person``.
+Classes are almost always named with capitalized names though this is a matter
+of style, not a rule of the language. Here is the basic skeleton of a ``Person``
+class:
.. code-block:: java
- public class House
+ public class Person
{
- // define class here - a blueprint
-
+ // define class here - also called the “body” of the class
+
}
-
- House myHouse = new House();
- House neighborsHouse = new House();
+You can create instances of the ``Person`` class with ``new`` as in ``new
+Person()`` And you can declare variables that can hold a reference to a
+``Person`` object with ``Person variableName``.
-Remember that objects have attributes and behaviors. These correspond to **instance variables** and **methods** in the class definition. Instance variables hold the data for objects where as the methods code the behaviors or the actions the object can do. A class also has **constructors** which initialize the instance variables when the object is created, for example new House() above. And a class can also have a **main method** which can be used to test the class.
+Or put it altogether to declare some variables and initialize each one with a
+reference to a new ``Person`` as shown here.
-Let's create a class called Person. What would we want to know about a person? What we want to know depends on what problem we are trying to solve. In one situation, perhaps when creating an address book, we might want to know the person's name and phone number and email. Here's a possible Person class with instance variables, constructor, and methods.
+.. code-block:: java
-.. figure:: Figures/personClassDefn.png
- :width: 500px
- :align: center
- :alt: Person
- :figclass: align-center
+ Person ada = new Person();
+ Person charles = new Person();
+
+So what makes up the body of the class—the stuff between the ``{}``\
+s?
+
+Remember that objects have both attributes and behaviors. These correspond to
+**instance variables** and **methods** in the class definition.
+
+The first things we define in a class are usually the instance variables. They
+are called that because each instance of the class (each object) has its own set
+of variables that aren’t shared with other instances. This is what allowed
+``yertle`` and ``myrtle`` from Unit 2 to be at different positions at the same
+time; they each had their own x position and y position instance variables.
+
+The next thing we define in a class is usually its **constructors**. We’ll talk
+about writing constructors in more detail in the next section but a
+constructor’s job is to initialize the instance variables when the object is
+created. Usually that will mean they need to take arguments. (The call to ``new
+Person()`` before is to a constructor that doesn’t take any arguments. In a
+moment we’ll see that our ``Person`` constructor will actually need arguments.)
+
+The real meat of a class is in the **methods** which define the behaviors of the
+objects of that class. Recall from Unit 2 that most methods either do things
+(like the ``Turtle`` methods that moved the turtle on the screen) or return
+values like the ``getXPos`` and ``getYPos`` on ``Turtle``.
+
+The methods of the class share access to the object’s instance variables and
+when a method is called on an object it uses the instance variables for that
+object. For example in the ``Turtle`` class the ``forward`` method changes an
+instance variable ``xPos``. When you call ``forward`` on ``yertle`` it changes
+``xPos`` on the ``yertle`` object and when you call it on ``myrtle`` it changes
+the ``xPos`` on the ``myrtle`` object.
+
+Putting it all together, the three main anatomical features of a class are the
+**instance variables** which hold values associated with each object, the
+**constructors** whose job is to initialize the instance variables, and the
+**methods** who contain the code that gives the objects their behavior and which
+can use the instance variables defined in the class.
- Figure 1: Person class
+.. code-block:: java
-Run the code below to see how it constructs 2 Person objects and fills in their data. We will explain all parts of this class in the next sections, but notice that execution always starts in the main method. When a method like the print() method is called, we run the code in the print method for that object. After a method is done, the control returns back to the next line of code in the main method. You can also see this in the |Java visualizer| (click on the link and then Forward at the bottom to run the code step by step).
+ public class Person
+ {
+ // instance variables
+ // constructors
-.. |Java visualizer| raw:: html
+ // methods
- Java visualizer
+ }
+And finally one last bit of weird anatomy, kind of like the appendix: any Java
+class can have a ``main`` method which can be used to run that class as a
+program either to test that one class or sometimes as the entry point to a whole
+program made up of many classes and objects.
+
+Designing a Class
+-----------------
+
+Now that we know what the skeleton of a class looks like and the elements that
+make up the body of the class, we’re ready to create our own class. Let’s start
+with a quick look at how to design a class such as ``Person``.
+
+One important question we have to ask when designing a class is, what data does
+it represent? In this case we can ask, what would we want to know about a
+person? Our answer will depend on what problem we are trying to solve. In one
+program, perhaps an address book, we might want to know the person's name and
+phone number and email. In another program, such as a medical application, we
+might need to know their vital signs such as their blood pressure, temperature,
+and pulse rate.
+
+For now let’s go with the address book example. Here's a fleshed out ``Person``
+class with instance variables, a constructor, and methods. We’ll go through the
+details in the next few sections but for now you can run the code to see how it
+constructs 2 ``Person`` objects and fills in their data.
+
+Remember that execution always starts in the ``main`` method. When a method like
+``print`` is called, the code defined in the method runs but when it gets the
+values of ``name``, ``email``, and ``phoneNumber`` it gets the specific values
+of those variables that were set by the constructor when the particular object
+we called ``print`` on was created. Click on the Show CodeLens button below and
+the Next button to run the code step by step.
.. activecode:: PersonClass
:language: java
:autograde: unittest
-
- Run the following class. Try changing the Person p2 object in main to your name.
+
+ Run the following class. Try changing the Person p2 object in main to your name.
+ Click on the Show CodeLens button and then Next to step through the code.
~~~~
- public class Person
+ public class Person
{
- // instance variables
- private String name;
- private String email;
- private String phoneNumber;
-
- // constructor: construct a Person copying in the data into the instance variables
- public Person(String initName, String initEmail, String initPhone)
- {
- name = initName;
- email = initEmail;
- phoneNumber = initPhone;
- }
-
- // Print all the data for a person
- public void print()
- {
- System.out.println("Name: " + name);
- System.out.println("Email: " + email);
- System.out.println("Phone Number: " + phoneNumber);
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // call the constructor to create a new person
- Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
- // call p1's print method
- p1.print();
- Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955");
- p2.print();
- }
+ // instance variables
+ private String name;
+ private String email;
+ private String phoneNumber;
+
+ // constructor: construct a Person copying in the data into the instance
+ // variables
+ public Person(String initName, String initEmail, String initPhone)
+ {
+ name = initName;
+ email = initEmail;
+ phoneNumber = initPhone;
+ }
+
+ // Print all the data for a person
+ public void print()
+ {
+ System.out.println("Name: " + name);
+ System.out.println("Email: " + email);
+ System.out.println("Phone Number: " + phoneNumber);
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // call the constructor to create a new person
+ Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
+ // call p1's print method
+ p1.print();
+ Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955");
+ p2.print();
+ }
}
-
+
====
// Test for Lesson 5.1.0 - Person class - should pass if/when they run code
import static org.junit.Assert.*;
- import org.junit.*;;
+
+ import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Name: Sana\nEmail: sana@gmail.com\nPhone Number: 123-456-7890\nName: Jean\nEmail: jean@gmail.com\nPhone Number: 404 899-9955";
-
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "Name: Sana\n"
+ + "Email: sana@gmail.com\n"
+ + "Phone Number: 123-456-7890\n"
+ + "Name: Jean\n"
+ + "Email: jean@gmail.com\n"
+ + "Phone Number: 404 899-9955";
+
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
}
-
-
-
-
Instance Variables
---------------------------
-.. index::
- pair: class; instance variables
+.. index::
+ pair: class; instance variables
-**Instance Variables** hold the data for an object. They record what an object needs to know to do work in the program. Instance variables are also called **attributes**, **fields**, or **properties**.
+As we’ve said, **instance Variables** hold the data for an object. They record
+what an object needs to know to play its role in the program. Instance variables
+are also sometimes called **attributes**, **fields**, or **properties**.
-Instance variables in general and 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 instance variable values.
+In general and definitely on the AP CSA exam, instance variables should be
+declared **private**. Think of ``private`` as like your diary. Only you should
+have direct access to it. Similarly, in Java a ``private`` instance variable can
+only be accessed by code in the class that declares the variable.
.. note::
-
+
Instance variables are declared right after the class declaration. They usually start with ``private`` then the *type* of the variable and then a *name* for the variable. Private means only the code in this class has access to it.
-The ``Person`` class declares 3 private instance variables: name, email, and phoneNumber. These are things that you might want to know about a person. They are declared at the top of the class and they exist inside the { } of the class. The methods of the class share the instance variables. They can access and use them.
+The ``Person`` class declares 3 private instance variables: ``name``, ``email``,
+and ``phoneNumber``. These are things that you might want to know about a
+person. They are declared at the top of the class and they exist inside the ``{
+}`` of the class.
-Once we have created a class like Person, we can have many objects declared of the class. The class is like a blueprint or cookie cutter that defines the variables and methods for that class. Each object will have their own copies of the same instance variables but with possibly different values in them (as seen in the cookie decorations below).
+Once we have created a class like ``Person``, we can create many instances
+(objects) of the class. The class is like a blueprint or cookie cutter that
+defines the variables and methods for that class. Each object will have their
+own copies of the same instance variables but with possibly different values in
+them (as seen in the cookie decorations below).
.. figure:: Figures/PersonClassWithCookies.png
@@ -172,9 +255,23 @@ Once we have created a class like Person, we can have many objects declared of t
Figure 2: Person Class and Objects
-**Object-oriented Programming** stresses **data encapsulation** where the data (instance variables) and the code acting on the data (methods) are wrapped together into a single unit and the implementation details are hidden. The data is protected from harm by being kept private. Anything outside the class can only interact with the public methods and cannot interact directly with the private instance variables (encapsulated in the pink box above).
+Good Java style stresses **data encapsulation** where the data (instance
+variables) and the code acting on the data (methods) are wrapped together into a
+single unit and the implementation details are hidden. Because only code in the
+class can access or change the values of ``private`` instance variables it is a
+lot easier to keep track of how your program works than if you had to worry that
+any code anywhere in a much larger program could possibly change the values of
+the variables.
-When designing a class, programmers make decisions about what data to make accessible and/or modifiable from an external class. The private access modifier is used to encapsulate and protect the data from external access. Private instance variables can only be accessed by methods within the class in which they are defined.
+Code in other classes can only interact with the ``public`` methods you provide
+and cannot directly access the ``private`` instance variables (shown in the pink
+box above).
+
+When designing a class you get to decide what data to make accessible or
+modifiable from other classes by what ``public`` methods you provide. (Remember
+from Unit 2 how the ``Turtle`` class provided ``getXPos`` and ``getYPos`` to get
+the turtle’s position but no ``setXPos`` and ``setYPos`` since the only way to
+move a turtle is through ``forward`` and ``moveTo`` methods?)
|Exercise| **Check Your Understanding**
@@ -183,57 +280,79 @@ When designing a class, programmers make decisions about what data to make acces
:iscode:
:feedback: Remember, instance variables are private and are declared after the class declaration.
- :click-incorrect:public class Name {:endclick:
-
+ :click-incorrect:public class Name:endclick:
+ :click-incorrect:{:endclick:
:click-correct:private String first;:endclick:
:click-correct:private String last;:endclick:
-
- :click-incorrect:public Name(String theFirst, String theLast) {:endclick:
+
+ :click-incorrect:public Name(String theFirst, String theLast):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:first = theFirst;:endclick:
:click-incorrect:last = theLast;:endclick:
:click-incorrect:}:endclick:
-
- :click-incorrect:public void setFirst(String theFirst) {:endclick:
+
+ :click-incorrect:public void setFirst(String theFirst):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:first = theFirst;:endclick:
:click-incorrect:}:endclick:
-
- :click-incorrect:public void setLast(String theLast) {:endclick:
- :click-incorrect:first = theLast;:endclick:
+
+ :click-incorrect:public void setLast(String theLast):endclick:
+ :click-incorrect:{:endclick:
+ :click-incorrect:last = theLast;:endclick:
:click-incorrect:}:endclick:
-
- :click-incorrect:}:endclick:
-
+
+ :click-incorrect:}:endclick:
+
+
-
Methods
-------
-.. index::
- pair: class; method
-
-**Methods** define what an object can do or the behavior of the object. Most methods are ``public`` which means they can be accessed from outside the class. Some methods can be marked as``private`` if they are helper methods that are just used internally by other methods inside the same class. They will not be accessible outside of the class. The private and public keywords determine the external access and visibility of classes, data, constructors, and methods.
+.. index::
+ pair: class; method
-.. note::
+Now to **methods** which define what we can actually do with an object. The most
+important methods in a class are the ``public`` methods since they can be
+accessed from outside the class. You may also write ``private`` methods that are
+not accessible outside of the class and therefore can only be used by other
+methods inside the same class. As you’ve probably figured out, the ``public``
+and ``private`` keywords determine the external access and visibility of
+classes, instance variables, constructors, and methods.
- Methods define what the object can do. They typically start with ``public`` then a type, then the name of the method followed by parentheses for optional parameters. Methods defined for an object can access and use its instance variables!
-
-The ``Person`` class above has a constructor called Person() which we will discuss in the next lesson, a print() method for output, and a main method which runs the whole program. We will also discuss **accessor** (also called getters) and **mutator** (also called setters or modifier) methods in the next lessons which allow get and set access to the instance variables.
+.. note::
-Here is an example of the print() method that prints out all the data stored for a person object. Notice that it starts with public and then the return type.
-The **void** return type is used to indicate that the method does not return anything. Then it has the method name followed by parentheses for possible parameters. The body of the method is in curly brackets. Notice that the method can access and use the instance variables in the class: name, email, and phoneNumber. The instance variables are shared by all the methods of the class.
+ Methods define what the object can do. They typically start with ``public``
+ then a type, then the name of the method followed by parentheses for optional
+ parameters. Methods defined for an object can access and use its instance
+ variables!
+
+The ``Person`` class above has a ``print`` method that prints out all the data
+stored for a person object. Notice that it is marked as ``public`` and after
+``public`` comes the return type. The ``void`` return type, as you may recall
+from Unit 2, is used to indicate that the method does not return anything but
+has some effect such as printing to the screen. After the return type comes the
+method name followed by parentheses containing the list of parameters. In this
+case there are no parameters but we still need the ``()``\ s. The body of the
+method is in ``{}``\ s. As we’ve discussed, the method can access and use the
+instance variables defined in the class: ``name``, ``email``, and
+``phoneNumber`` but will get the values specific to the object we called
+``print`` on.
.. code-block:: java
-
+
public void print()
{
System.out.println("Name: " + name);
System.out.println("Email: " + email);
System.out.println("Phone Number: " + phoneNumber);
}
-
-To call a method to do its job, we create an object of the class and then use the dot (.) operator to call its public methods, for example p1.print() means call p1's print method.
+
+To call a method, we need an object that is an instance of the class such as we
+get by calling its constructor. Then we use the dot (``.``) operator to call its
+``public`` methods, for example ``p1.print()`` means call the ``print`` method
+on the object ``p1``.
.. code-block:: java
@@ -241,8 +360,8 @@ To call a method to do its job, we create an object of the class and then use th
Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
// call p1's print method
p1.print();
-
-
+
+
|Exercise| Check Your Understanding
.. clickablearea:: name_methods
@@ -250,39 +369,63 @@ To call a method to do its job, we create an object of the class and then use th
: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:public class Name:endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:private String first;:endclick:
:click-incorrect:private String last;:endclick:
-
- :click-incorrect:public Name(String theFirst, String theLast) {:endclick:
+
+ :click-incorrect:public Name(String theFirst, String theLast):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:first = theFirst;:endclick:
:click-incorrect:last = theLast;:endclick:
- :click-incorrect:}:endclick:
-
- :click-correct:public void setFirst(String theFirst) {:endclick:
- :click-correct: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:
+ :click-incorrect:}:endclick:
-Object-Oriented Design
-----------------------
-
-.. |tutorial on class diagrams| raw:: html
-
- tutorial on class diagrams
+ :click-correct:public void setFirst(String theFirst):endclick:
+ :click-correct:{:endclick:
+ :click-correct:first = theFirst;:endclick:
+ :click-correct:}:endclick:
-.. |Creately.com| raw:: html
+ :click-correct:public void setLast(String theLast):endclick:
+ :click-correct:{:endclick:
+ :click-correct:last = theLast;:endclick:
+ :click-correct:}:endclick:
- Creately.com
+ :click-incorrect:}:endclick:
+Object-Oriented Design
+----------------------
-In **Object-Oriented Design** (OOD), programmers first spend time to decide which classes are needed and then figure out the data and methods in each class. For example, here is the class diagram for the Turtle class that we have seen before. The - in front of the attributes indicate that they are private, and the + in front of the methods indicate that they are public. Here is a |tutorial on class diagrams| that explains it in more detail if you are curious (Class diagrams are not on the AP CS A exam). If you want to draw your own, |Creately.com| is a good free online drawing tool for class diagrams.
+So far we’ve just talked about designing one class. In **object-oriented
+design** (OOD), programmers often start by deciding which classes are needed to
+solve a problem and then figure out the data and methods in each class.
+
+When you are given a problem specification, you can identify classes you’ll need
+by looking for the **nouns** in the specification. For instance, the
+specification for the turtle graphics system from Unit 2 probably contained a
+sentence that said something like, “there are turtles that can exist on a
+2-dimensional world and can draw lines by moving around the world”. The main
+nouns in that description are “turtle” and “world” and indeed the classes in the
+system are ``Turtle`` and ``World``. (The one noun that was not turned into a
+class was “line”. Do you think it would have made sense to create a ``Line``
+class? Why or why not?)
+
+Once you’ve determined the classes you need, then you can go through the process
+we described above to design the individual classes. Note that you can often
+identify methods that should exist on classes by looking for verbs in the
+specification like “move”.
+
+Sometimes it’s useful, when designing a complex system with lots of classes, to
+make diagrams of the classes that show you at a glance what instance variables
+and methods they have. Often these can just be sketches in your notebook or on a
+whiteboard but there are also more formal systems such as the Unified Modeling
+Language (UML) for drawing these diagrams.
+
+For example, here is a UML class diagram for the ``Turtle`` class. The ``-`` in
+front of the attributes indicate that they are private, and the ``+`` in front
+of the methods indicate that they are public. Here is a |tutorial on class
+diagrams| that explains it in more detail if you are curious (Class diagrams are
+not on the AP CSA exam). If you want to draw your own, |app diagrams| or
+|Creately.com| are good free online drawing tools for UML class diagrams.
.. figure:: Figures/turtleUMLClassDiagram.png
@@ -292,15 +435,14 @@ In **Object-Oriented Design** (OOD), programmers first spend time to decide whic
:figclass: align-center
Figure 3: Turtle Class Diagram
-
-When you are given a problem specification, look for the **nouns** to identify what classes you need to create. For an example, try the problem below.
+
|Exercise| **Check Your Understanding**
.. shortanswer:: OOD1
- You've been hired by your school to create a program that keeps track of "students at your school and the courses they are taking". Name 2 classes that you would create in your program. Name 2 attributes (data kept in instance variables) for each class.
-
+ You've been hired by your school to create a program that keeps track of "students at your school and the courses they are taking". Name 2 classes that you would create in your program. Name 2 attributes (data kept in instance variables) for each class.
+
The two nouns in the problem description above, **Student** and **Course** would make good class names! Then, you can think about what data you need to keep track of for students and courses and what methods you need. Note that the instance variables in the Person class could also work for a Student class!
@@ -313,7 +455,6 @@ The two nouns in the problem description above, **Student** and **Course** would
.. shortanswer:: OOD2
Say you wanted to make a computer game from a board game that you are playing. Think about what objects are in the game. For example, here is the description for Monopoly (trademark Hasbro games): "Buy, sell, dream and scheme your way to riches. Players buy, sell and trade to win. Build houses and hotels on your properties and bankrupt your opponents to win it all. Chance and Community Chest cards can change everything." What classes would you need to create a computer version of this game? (Remember to look for the nouns). Take one of the classes you listed, and try to come up with 2 pieces of data in that class that will be the instance variables.
-
|Groupwork| Programming Challenge : Riddle Class
----------------------------------------------------------
@@ -328,11 +469,11 @@ In this project, you will create a class that can tell riddles like the followin
- Riddle Question: Why did the chicken cross the playground?
- Riddle Answer: To get to the other slide!
-1. First, brainstorm in pairs to do the **Object-Oriented Design** for a riddle asking program. What should we call this class? What data does it need to keep track of in instance variables? What is the data type for the instance variables? What methods do we need? (You could draw a Class Diagram for this class using |Creately.com|, although it is not required).
+1. First, brainstorm in pairs to create an **object-oriented design** for a riddle asking program. What should we call this class? What data does it need to keep track of in instance variables? What is the data type for the instance variables? What methods do we need? (You could draw a Class Diagram for this class using |app diagrams| or |Creately.com|, although it is not required).
-2. Using the Person class above as a guide, write a Riddle class in the Active Code template below that has 2 instance variables for the riddle's question and answer, a constructor that initializes the riddle, and 2 methods to ask the riddle and answer the riddle. Hint: Don't name your instance variables initQuestion and initAnswer -- we'll explain why shortly. If you came up with other instance variables and methods for this class, you can add those too! Don't forget to specify the private or public access modifiers. Use the outline in the Active Code below. You will learn how to write constructors and other methods in detail in the next lessons.
+2. Using the ``Person`` class above as a guide, write a ``Riddle`` class in the Active Code template below that has 2 instance variables for the riddle's question and answer, a constructor that initializes the riddle, and 2 methods to ask the riddle and answer the riddle. Don't name your instance variables ``initQuestion`` and ``initAnswer`` since they are used as constructor parameter variables. If you came up with other instance variables and methods for this class, you can add those too! Don't forget to specify the ``private`` or ``public`` access modifiers. Use the outline in the Active Code below. You will learn how to write constructors and other methods in detail in the next lessons.
-3. Complete the main method to construct at least 2 Riddle objects and call their printQuestion() and printAnswer() methods to ask and answer the riddle. You can look up some good riddles online.
+3. Complete the ``main`` method to construct at least 2 ``Riddle`` objects that call the ``Riddle`` constructor with the arguments for the riddle question and answer and call their ``printQuestion`` and ``printAnswer`` methods to ask and answer the riddle. You can look up some good riddles online.
@@ -340,165 +481,234 @@ In this project, you will create a class that can tell riddles like the followin
:language: java
:autograde: unittest
- Complete the Riddle class below and complete the main method to construct 2 Riddle objects and call their printQuestion() and printAnswer() methods.
+ Complete the Riddle class below and complete the main method to construct 2 Riddle objects and call their printQuestion() and printAnswer() methods.
~~~~
public class Riddle
{
- // write 2 instance variables for Riddle's question and answer: private type variableName;
-
-
- // constructor
- public Riddle(String initQuestion, String initAnswer)
- {
- // set the instance variables to the init parameter variables
-
- }
-
- // Print riddle question
- public void printQuestion()
- {
- // print out the riddle question with System.out.println
-
- }
-
- // Print riddle answer
- public void printAnswer()
- {
- // print out the riddle answer with System.out.println
-
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // call the constructor to create 2 new Riddle objects
-
- // call their printQuestion() and printAnswer methods
-
- }
+ // write 2 instance variables for Riddle's question and answer: private type
+ // variableName;
+
+ // constructor
+ public Riddle(String initQuestion, String initAnswer)
+ {
+ // set the instance variables to the init parameter variables
+
+ }
+
+ // Print riddle question
+ public void printQuestion()
+ {
+ // print out the riddle question with System.out.println
+
+ }
+
+ // Print riddle answer
+ public void printAnswer()
+ {
+ // print out the riddle answer with System.out.println
+
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // call the Riddle constructor to create 2 new Riddle objects
+ // with the arguments for the riddle question and answer.
+
+ // call the riddle objects' printQuestion() and printAnswer methods
+
+ }
}
-
+
====
// Test Code for Lesson 5.1.5 - Riddle
// @author Kate McDonnell
// Test Code for Lesson 5.1.5 - Riddle
import static org.junit.Assert.*;
+
import org.junit.*;
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests()
- {
- super("Riddle"); // class name / location of main
-
- Object[] values = new Object[]{"Question", "Answer"};
- setDefaultValues(values);
- }
+ public RunestoneTests()
+ {
+ super("Riddle"); // class name / location of main
+
+ Object[] values = new Object[] {"Question", "Answer"};
+ setDefaultValues(values);
+ }
+
+ @Test
+ public void testPrintQuestion()
+ {
+ String output = getMethodOutput("printQuestion");
+ String expect = "Question";
+
+ boolean passed = getResults(expect, output, "Checking method printQuestion()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrintAnswer()
+ {
+ String output = getMethodOutput("printAnswer");
+ String expect = "Answer";
+
+ boolean passed = getResults(expect, output, "Checking method printAnswer()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCallConstructors()
+ {
+ String code = getCodeWithoutComments();
+ String search = "= new Riddle(";
+
+ int num = countOccurences(code, search);
+
+ String expect = search + "...) x 2";
+ String actual = search + "...) x " + num;
+
+ boolean passed = getResults(expect, actual, "Checking that you made 2 Riddle objects");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testVariableTypes()
+ {
+ String varTypes = "String String";
+ String output = testInstanceVariableTypes(varTypes.split(" "));
+
+ boolean passed = getResults(varTypes, output, "Checking Instance Variable Type(s)");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "2 Private";
+ String output = testPrivateInstanceVariables();
+
+ boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+
+ String expect = "2+ line(s) of text";
+ String actual = " line(s) of text";
+
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 2;
+
+ getResults(expect, actual, "Checking main method", passed);
+ assertTrue(passed);
+ }
+ }
- @Test
- public void testPrintQuestion()
- {
- String output = getMethodOutput("printQuestion");
- String expect = "Question";
+|Groupwork| Design a Class for your Community
+----------------------------------------------------------
- boolean passed = getResults(expect, output, "Checking method printQuestion()");
- assertTrue(passed);
- }
+.. |worksheet| raw:: html
- @Test
- public void testPrintAnswer()
- {
- String output = getMethodOutput("printAnswer");
- String expect = "Answer";
+ worksheet
- boolean passed = getResults(expect, output, "Checking method printAnswer()");
- assertTrue(passed);
- }
-
- @Test
- public void testDefaultConstructor()
- {
- String[] args = {"Question 1", "Answer 1"};
- String output = checkDefaultConstructor();
- String expect = "fail";
+.. |community1| raw:: html
- boolean passed = getResults(expect, output, "Checking default constructor");
- assertTrue(passed);
- }
+ Lesson 5.19
- @Test
- public void testConstructor()
- {
- String[] args = {"Question 1", "Answer 1"};
- String output = checkConstructor(args);
- String expect = "pass";
+In this unit, you will design a class of your own choice that is relevant to your community.
+You will improve the class in each lesson of this unit. We suggest that you work in pairs on this project.
+If you would rather work on this project as 1 stand-alone lab project rather than a piece at a time at the end of each lesson,
+you can do this in |community1| at the end of Unit 5.
- boolean passed = getResults(expect, output, "Checking constructor with parameters");
- assertTrue(passed);
- }
+1. Make your own copy of this |worksheet| from the File menu. For question 1, brainstorm and ask people in your community what would be important or useful for them to track in a community organization or activity or to help your community. For example, you could create a Java class to keep track of community events, club activities, athletic games or statistics, community leaders, performers or performances, health tracking, or another subject of your choice.
- @Test
- public void testVariableTypes()
- {
- String varTypes = "String String";
- String output = testInstanceVariableTypes(varTypes.split(" "));
+2. Come up with the class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing). Come up with at least 3 instance variables that are attributes of things in that class. Think about what data type each variable should be.You can use the |worksheet| to design your class. Optionally, you may want to draw a UML class diagram for your class on paper or using |app diagrams| or |Creately.com| (see |tutorial on class diagrams|).
- boolean passed = getResults(varTypes, output, "Checking Instance Variable Type(s)");
- assertTrue(passed);
- }
+3. Type in your class name and declare the instance variables for your class in the active code exercise below. Click on run. Your class will not print out anything yet, but it should run without errors. You will add constructors and other methods to this class in the next lessons.
- @Test
- public void testPrivateVariables()
- {
- String expect = "2 Private";
- String output = testPrivateInstanceVariables();
- boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)");
- assertTrue(passed);
- }
+.. activecode:: community-challenge-5-1
+ :language: java
+ :autograde: unittest
+ Come up with the class name for your community data-tracking class (it should be a category of people or things, not a specific person or thing) and at least 3 instance variables that are attributes of things in that class. Your class will not print out anything yet, but it should run without errors.
+ ~~~~
+ public class // Add your class name here!
+ {
+ // write 3 instance variables for class: private type variableName;
- @Test
- public void testMain()
- {
- String output = getMethodOutput("main");
- String expect = "2+ line(s) of text";
- String actual = " line(s) of text";
- int len = output.split("\n").length;
+ public static void main(String[] args)
+ {
+ // Run your code to check for errors.
+ // It will not print anything yet.
+ // You will add more in the next lesson.
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
- if (output.length() > 0) {
- actual = len + actual;
- } else {
- actual = output.length() + actual;
- }
- boolean passed = len >= 2;
+ import org.junit.*;
- getResults(expect, actual, "Checking main method", passed);
- assertTrue(passed);
- }
- }
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "3 Private";
+ String output = testPrivateInstanceVariables();
+ boolean passed = false;
+ if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1)))
+ passed = true;
+ passed = getResults(expect, output, "Checking private instance variable(s)", passed);
+ assertTrue(passed);
+ }
+ }
Summary
----------
-- Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
+- Programmers use code to represent a physical object or nonphysical concept,
+ real or imagined, by defining a class based on the attributes and/or behaviors
+ of the object or concept.
-- **Instance Variables** define the attributes or data needed for objects, and **methods** define the behaviors or functions of the object.
+- **Instance Variables** define the attributes or data needed for objects, and
+ **methods** define the behaviors or functions of the object.
-- **Data encapsulation** is a technique in which the implementation details of a class are kept hidden from the user. The data is kept private with access only through the public methods that can act on the data in the class.
+- **Data encapsulation** is a technique in which the implementation details of a
+ class are kept hidden from the user. The data is kept private with access only
+ through the public methods that can act on the data in the class.
-- The keywords **public** and **private** affect the access of classes, data, constructors, and methods.
+- The keywords ``public`` and ``private`` affect the access of classes, data,
+ constructors, and methods.
-- The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
+- The keyword ``private`` restricts access to the declaring class, while the
+ keyword ``public`` allows access from classes outside the declaring class.
-- Instance variables are encapsulated by using the **private access modifier**.
+- Instance variables are encapsulated by using the ``private`` **access
+ modifier**.
-- Methods can be public or private, but they are usually public.
+- Methods can be ``public`` or ``private``. The set of ``public`` methods define
+ what other classes can do with an instance of a class.
AP Practice
------------
@@ -511,19 +721,19 @@ AP Practice
Consider the Cat class which will contain a String and an int attribute for a cat’s name and age and a constructor.
.. code-block:: java
-
+
public class Cat
{
- /* missing code */
+ /* missing code */
}
-
- Which of the following replacements for /* missing code */ is the most appropriate
- implementation of the class?
+
+ Which of the following replacements for /* missing code \*/ is the most appropriate
+ implementation of the class?
- .. code-block:: java
public String name;
- private int age;
+ public int age;
private Cat(String name, int age)
{ /* implementation not shown */ }
@@ -557,31 +767,31 @@ AP Practice
- Instance variables should be private.
- .. code-block:: java
-
+
private String name;
private int age;
private Cat(String name, int age)
{ /* implementation not shown */ }
- - Constructor should be public.
+ - Constructor should be public.
.. mchoice:: AP5-1-2
:practice: T
Consider the Party class below which will contain three int attributes for numOfPeople, volumeOfMusic, and numOfBoxesOfPizza, a constructor, and a startParty method. The startParty method is intended to be accessed outside the class.
-
+
.. code-block:: java
public class Party
{
- /* missing code */
+ /* missing code */
}
- Which of the following replacements for /* missing code */ is the most appropriate
- implementation of the class?
+ Which of the following replacements for /* missing code \*/ is the most appropriate
+ implementation of the class?
- .. code-block:: java
-
+
private int numOfPeople;
private int volumeOfMusic;
private int numOfBoxesOfPizza;
@@ -591,9 +801,9 @@ AP Practice
{ /* implementation not shown */ }
- Method startParty() should be public.
-
+
- .. code-block:: java
-
+
private int numOfPeople;
private int volumeOfMusic;
private int numOfBoxesOfPizza;
@@ -603,9 +813,9 @@ AP Practice
{ /* implementation not shown */ }
+ Correct, instance variables should be private and the methods should be public.
-
+
- .. code-block:: java
-
+
public int numOfPeople;
public int volumeOfMusic;
public int numOfBoxesOfPizza;
@@ -615,9 +825,9 @@ AP Practice
{ /* implementation not shown */ }
- Instance variables should be private.
-
+
- .. code-block:: java
-
+
private int numOfPeople;
private int volumeOfMusic;
private int numOfBoxesOfPizza;
@@ -629,3 +839,14 @@ AP Practice
- Methods should be public.
+.. |tutorial on class diagrams| raw:: html
+
+ tutorial on class diagrams
+
+.. |Creately.com| raw:: html
+
+ Creately.com
+
+.. |app diagrams| raw:: html
+
+ app.diagrams.net
diff --git a/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst b/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst
index 376f58336..369cbd958 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-10-social-impacts.rst
@@ -1,37 +1,23 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-10-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
+|Time45|
+
Social Impacts of CS
====================
.. |ACM professional code of ethics| raw:: html
ACM professional code of ethics
-
+
.. |Wired article| raw:: html
Wired article
-We are living in an age of rapid development in technology and automation. Software and hardware developers increasingly have real impacts on people's lives. In computer science, we follow the following |ACM professional code of ethics| which includes guidelines such as "Avoid harm" and "Respect privacy".
+We are living in an age of rapid development in technology and automation. Software and hardware developers increasingly have real impacts on people's lives. In computer science, we follow the following |ACM professional code of ethics| which includes guidelines such as "Avoid harm" and "Respect privacy".
However, sometimes programs have unintended consequences, and sometimes, it is hard to ensure **system reliability**, where everything will work as intended. Software developers also need to be aware of the legal implications and intellectual property laws.
@@ -43,18 +29,18 @@ Another problem in machine learning is **bias** in algorithms or data. Machine l
.. |video1| raw:: html
Gender Shades video
-
+
.. |Joy Buolamwini| raw:: html
Joy Buolamwini
-
-Watch the following |video1| about gender and race bias in face recognition algorithms by computer scientist |Joy Buolamwini| (MIT Media Lab and Algorithmic Justice League).
+
+Watch the following |video1| about gender and race bias in face recognition algorithms by computer scientist |Joy Buolamwini| (MIT Media Lab and Algorithmic Justice League).
.. youtube:: TWWsW1w-BVo
- :height: 315
- :width: 560
+ :height: 400
+ :width: 600
:align: left
-
+
Here are some other interesting videos to watch about bias in algorithms:
@@ -80,4 +66,4 @@ Summary
- Legal issues and intellectual property concerns arise when creating programs.
-- The creation of programs has impacts on society, economies, and culture. These impacts can be beneficial and/or harmful.
\ No newline at end of file
+- The creation of programs has impacts on society, economies, and culture. These impacts can be beneficial and/or harmful.
diff --git a/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst b/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst
index c4d7a76c1..4eefe7cd7 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-11-summary.rst
@@ -1,34 +1,34 @@
.. qnum::
:prefix: 5-11-
:start: 1
-
+
Unit 5 Summary
================
-.. index::
+.. index::
single: class
single: compiler
- single: compile time error
- single: field
- single: Java
- single: main method
- single: method
- single: object
- single: syntax error
- single: private
- single: public
+ single: compile time error
+ single: field
+ single: Java
+ single: main method
+ single: method
+ single: object
+ single: syntax error
+ single: private
+ single: public
Concept Summary
---------------
- **Class** - A class defines a type and is used to define what all objects of that class know and can do.
-- **Compiler** - Software that translates the Java source code (ends in .java) into the Java class file (ends in .class).
-- **Compile time error** - An error that is found during the compilation. These are also called syntax errors.
-- **Constructor** - Used to initialize fields in a newly created object.
+- **Compiler** - Software that translates the Java source code (ends in .java) into the Java class file (ends in .class).
+- **Compile time error** - An error that is found during the compilation. These are also called syntax errors.
+- **Constructor** - Used to initialize fields in a newly created object.
- **Field** - A field holds data or a property - what an object knows or keeps track of.
-- **Java** - A programming language that you can use to tell a computer what to do.
+- **Java** - A programming language that you can use to tell a computer what to do.
- **Main Method** - Where execution starts in a Java program.
- **Method** - Defines behavior - what an object can do.
- **Object** - Objects do the actual work in an object-oriented program.
@@ -39,7 +39,7 @@ Java Keyword Summary
- **class** - used to define a new class
- **public** - a visibility keyword which is used to control the classes that have access. The keyword public means the code in any class has direct access.
-- **private** - a visibility keyword which is used to control the classes that have access. The keyword private means that only the code in the current class has direct access.
+- **private** - a visibility keyword which is used to control the classes that have access. The keyword private means that only the code in the current class has direct access.
@@ -48,28 +48,29 @@ Vocabulary Practice
.. dragndrop:: ch2_vocab1
:feedback: Review the summaries above.
- :match_1: does the actual work in an object-oriented program.|||object
+ :match_1: does the actual work in an object-oriented program.|||object
:match_2: defines a type|||class
:match_3: A programming language that you can use to tell a computer what to do.|||Java
:match_4: Translates a Java source file (ends in .java) into a Java class file (ends in .class)|||compiler
-
+
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:: ch2_vocab2
:feedback: Review the summaries above.
:match_1: initializes the fields of an object after it has been created|||constructor
:match_2: defines behavior|||method
:match_3: holds data or a property|||field
:match_4: where execution starts|||main method
-
+
Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct.
-
+
.. |Quizlet| raw:: html
Quizlet
For more practice, see this |Quizlet|.
+
Common Mistakes
----------------
diff --git a/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst b/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst
index cb8059b87..0d09717ff 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-2-writing-constructors.rst
@@ -1,119 +1,185 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-2-
:start: 1
-
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
+
+|Time45|
Writing Constructors
====================
-.. index::
- pair: class; constructor
-
-In Unit 2, we learned how to create objects using constructor. Objects are created in programs by declaring a variable of the class and using the keyword new followed by a call to a constructor. **Constructors** set the initial values for the object's instance variables. For example, here is how we create World, Turtle, and Person objects.
+.. index::
+ pair: class; constructor
-.. code-block:: java
+In Unit 2, we learned how to create objects by calling **constructors**. To
+review, a call to a constructor consists of the word ``new`` followed by the
+name of the class being constructed, and then an argument list in parentheses.
+For example, here is how we create ``World``, ``Turtle``, and ``Person``
+objects.
+
+.. code-block:: java
// To create a new object, write:
// ClassName variableName = new ConstructorName(arguments);
World world = new World();
Turtle t = new Turtle(world);
- Person p = new Person("Pat","pat@gmail.com","123-456-7890");
-
+ Person p = new Person("Pat", "pat@gmail.com", "123-456-7890");
+
+Now it's time to learn to write our own constructors.
-In a new class, constructors are usually written after the instance variables and before any methods. They typically start with ``public`` and then the *name* of the class: ``public ClassName()``. Unlike other methods, they do not have a return type, not even void, after the access modifier public. They can take **parameters** (specified in parentheses) for the data which is used to initialize the instance variables.
+Constructor Signature
+--------------------------------
-.. code-block:: java
+In the source code for a class, constructors are usually written after the
+instance variables and before any methods.
+
+The signature of a constructor is similar to the signature of a method except
+there is no return type, not even ``void``, and instead of a method name, the
+name of the constructor is the same as the name of the class. The constructors
+you write will almost always be marked ``public``. Like methods, constructors
+also have a **parameter list** specified in parenthesis that declare the
+variables that will be used to hold the arguments passed when the constructor is
+called.
+
+.. code-block:: java
public class ClassName
{
+ /* Instance variable declarations go here, before constructors */
- /* Instance Variable Declarations -- not shown */
+ /* Constructor - same name as Class, no return type */
+ public ClassName()
+ {
+ /* Implementation not shown */
+ }
- /* Constructor - same name as Class, no return type */
- public ClassName()
- {
- /* Implementation not shown */
- }
+ /* Method definitions go here, after constructors */
}
-
+
.. note::
Constructors must have the same name as the class! Constructors have no return type!
-
-Classes usually have more than one constructor. There are usually at least 2 constructors:
-- a constructor that takes no parameters
-- a constructor that takes all the parameters necessary for initializing all the instance variables
+The Job of a Constructor
+---------------------------------------
-The attributes of an object and their values at a given time define that object's state. The constructors initialize the object's state by assigning initial values to the instance variables that the object has as its attributes.
+The job of a constructor is to set the initial values for the object’s instance
+variables to useful values. But what does “useful” mean? Sometimes we describe
+the values of all an object's instance variables at a given time as the object's
+**state**. And we say an object is in a **valid state** when all its instance
+variables have values that let us use the object by invoking its public methods.
+So another way to describe the job of a constructor is to set the object’s
+instance values so it’s in a valid state and ready to be used.
-Here are two constructors that could be written for the Person class. Notice that the first one initializes name, email, and phoneNumber to empty string "" as the default values. Most programmers use "" as the default value for String variables and 0 as the default value for int and double variables.
+Classes can have zero or more constructors but they should all produce an object
+in a valid state.
-.. code-block:: java
+The easiest way to write a constructor is to *not* write one. If you do not
+write a constructor your class will automatically get what is called the
+**default no-argument constructor**. This constructor will initialize all your
+instance variables to the default value for their type: 0 for ``int`` and
+``double``, ``false`` for ``boolean``, and ``null`` for all reference types. If
+those default values are sufficient to put your object into a valid state you may
+not need to write a constructor at all.
- // default constructor: initialize instance vars to default empty strings
- public Person()
- {
- name = "";
- email = "";
- phoneNumber = "";
- }
+Usually, however, if you are writing a class that has instance variables, you
+need to initialize your instance values to some other values. In that case you
+probably need to write a constructor that takes arguments and uses them to
+initialize your instance variables.
- // constructor: initialize all 3 instance variables to parameters
- public Person(String initName, String initEmail, String initPhone)
- {
- name = initName;
- email = initEmail;
- phoneNumber = initPhone;
- }
+For example, consider the constructor from the ``Person`` class from the last
+section.
+
+.. code-block:: java
+
+ public Person(String initName, String initEmail, String initPhone)
+ {
+ name = initName;
+ email = initEmail;
+ phoneNumber = initPhone;
+ }
+
+This constructor ensures that all three of the instance variables (``name``, ``email``, and ``phoneNumber``) in ``Person``
+are initialized to the values provided by whatever code called the constructor. For example, in the constructor call
+``new Person("Pat", "pat@gmail.com", "123-456-7890")``, the argument "Pat" is passed into the parameter variable ``initName``,
+which the constructor then assigns to the instance variable ``name``.
+
+One important note: if you do write a constructor, Java will not generate the
+default constructor for you. This is a good thing because it lets you make sure
+that instances of your class are always properly initialized. With this
+constructor in place, for instance, there’s no way to construct a ``Person``
+object without providing the three required ``String`` values.
+
+Sometimes you will want to write more than one constructor so there are
+different ways of making an instance of your class. One reason to do that is to
+make it convenient to create instances from different kinds of arguments. This
+is called **overloading** and we discussed it in Chapter 2 from the perspective
+of calling constructors.
+
+For instance, suppose we were writing a program that had another class
+``AddressBookEntry`` which had getters for name, email, and phone number. In
+that program it might be useful to write another ``Person`` constructor like
+this:
+
+.. code-block:: java
+
+ public Person(AddressBookEntry address) {
+ {
+ name = address.getName();
+ email = address.getEmail();
+ phoneNumber = address.getPhoneNumber();
+ }
+
+Sometimes you might still even want to provide a no-argument constructor. If
+there’s a valid object that you can create without any arguments, you could
+write a no-argument constructor for ``Person`` like:
+
+.. code-block:: java
-If there are no constructors written for a class, Java provides a no-argument **default constructor** where the instance variables are set to their default values. For int and double variables, the default value used is **0**, and for String and other object variables, the default is **null**. However, if you do write at least one constructor, Java will not generate the default constructor for you, so you should write at least a constructor with no parameters and one with many parameters.
-
-
-|Exercise| **Check Your Understanding**
+ public Person()
+ {
+ name = "Anonymous";
+ email = "unknown";
+ phoneNumber = "unknown";
+ }
+
+
+It’s up to you to decide if this is actually a useful value to have or if it
+would be better to force the users of the ``Person`` class to choose the
+values themselves.
+
+
+|Exercise| **Check Your Understanding**
-
.. clickablearea:: name_constructor
:question: Click on all the lines of code that are part of constructors in the following class.
:iscode:
- :feedback: Constructors are public and have the same name as the class.
+ :feedback: Constructors are public and have the same name as the class.
- :click-incorrect:public class Name {:endclick:
-
+ :click-incorrect:public class Name:endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:private String first;:endclick:
:click-incorrect:private String last;:endclick:
-
- :click-correct:public Name(String theFirst, String theLast) {:endclick:
+
+ :click-correct:public Name(String theFirst, String theLast):endclick:
+ :click-correct:{:endclick:
:click-correct:first = theFirst;:endclick:
:click-correct:last = theLast;:endclick:
- :click-correct:}:endclick:
-
- :click-incorrect:public void setFirst(String theFirst) {:endclick:
+ :click-correct:}:endclick:
+
+ :click-incorrect:public void setFirst(String theFirst):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:first = theFirst;:endclick:
- :click-incorrect:}:endclick:
-
- :click-incorrect:public void setLast(String theLast) {:endclick:
+ :click-incorrect:}:endclick:
+
+ :click-incorrect:public void setLast(String theLast):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:last = theLast;:endclick:
- :click-incorrect:}:endclick:
-
- :click-incorrect:}:endclick:
-
+ :click-incorrect:}:endclick:
+
+ :click-incorrect:}:endclick:
+
.. mchoice:: qsse_5
:practice: T
:answer_a: Determines the amount of space needed for an object and creates the object
@@ -122,275 +188,294 @@ If there are no constructors written for a class, Java provides a no-argument **
:answer_d: Initialize the instance variables in the object
:correct: d
:feedback_a: The object is already created before the constructor is called but the constructor initializes the instance variables.
- :feedback_b: Constructors do not name the object.
+ :feedback_b: Constructors do not name the object.
:feedback_c: Constructors do not free any memory. In Java the freeing of memory is done when the object is no longer referenced.
:feedback_d: A constructor initializes the instance variables to their default values or in the case of a parameterized constructor, to the values passed in to the constructor.
-
+
What best describes the purpose of a class's constructor?
-
+
|CodingEx| **Coding Exercise**
+.. activecode:: class-Fraction
+ :language: java
+ :autograde: unittest
+
+ The following class defines a ``Fraction`` with the instance variables
+ ``numerator`` and ``denominator``. It uses 2 constructors. Note that the
+ no-argument constructor sets the default instance variable values to 1 rather
+ than 0 since a fraction with 0 in the denominator is not valid. Try to guess
+ what it will print before you run it. Hint! Remember to start with the
+ ``main`` method! You can also view it in the Java visualizer by clicking on
+ the Show CodeLens button below.
+ ~~~~
+ public class Fraction
+ {
+ // instance variables
+ private int numerator;
+ private int denominator;
-.. |Java visualizer| raw:: html
+ // constructor: set instance variables to default values
+ public Fraction()
+ {
+ numerator = 1;
+ denominator = 1;
+ }
- Java visualizer
+ // constructor: set instance variables to init parameters
+ public Fraction(int initNumerator, int initDenominator)
+ {
+ numerator = initNumerator;
+ denominator = initDenominator;
+ }
-.. activecode:: class-Fraction
- :language: java
- :autograde: unittest
+ // Print fraction
+ public void print()
+ {
+ System.out.println(numerator + "/" + denominator);
+ }
- The following class defines a Fraction with the instance variables numerator and denominator. It uses 2 constructors. Note that this constructor sets the default instance variable values to 1 rather than 0 -- so we don't end up with divide by zero. Try to guess what it will print before you run it. Hint! Remember to start with the main method! You can also view it in the |Java visualizer| by clicking on the Code Lens button below.
- ~~~~
- public class Fraction
- {
- // instance variables
- private int numerator;
- private int denominator;
-
- // constructor: set instance variables to default values
- public Fraction()
- {
- numerator = 1;
- denominator = 1;
- }
-
- // constructor: set instance variables to init parameters
- public Fraction(int initNumerator, int initDenominator)
- {
- numerator = initNumerator;
- denominator = initDenominator;
- }
-
- // Print fraction
- public void print()
- {
- System.out.println(numerator + "/" + denominator);
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- Fraction f1 = new Fraction();
- Fraction f2 = new Fraction(1,2);
- // What will these print out?
- f1.print();
- f2.print();
- }
- }
- ====
- // Test Code for Lesson 5.2.0.1 - Fraction
- import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
+ // main method for testing
+ public static void main(String[] args)
+ {
+ Fraction f1 = new Fraction();
+ Fraction f2 = new Fraction(1, 2);
+ // What will these print out?
+ f1.print();
+ f2.print();
+ }
+ }
- import java.io.*;
+ ====
+ // Test Code for Lesson 5.2.0.1 - Fraction
+ import static org.junit.Assert.*;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void test() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "1/1\n1/2";
+ import org.junit.Test;
- boolean passed = getResults(expect, output, "Running main", true);
- assertTrue(passed);
- }
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void test() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "1/1\n1/2";
+
+ boolean passed = getResults(expect, output, "Running main", true);
+ assertTrue(passed);
+ }
+ }
- }
-
|CodingEx| **Coding Exercise**
.. activecode:: class-Car
- :language: java
- :autograde: unittest
- :practice: T
-
- The following class defines a Car with the instance variables model and year, for example a Honda 2010 car. However, some of the code is missing. Fill in the code for the 2 constructors that are numbered 1 and 2. And fill in the code to call the constructors in the main method numbered 3. The car1 object should test the first constructor with default values and the car2 object should test the second constructor to create a Honda 2010 car. Run your program and make sure it works and prints out the information for both cars.
- ~~~~
- public class Car
- {
- // instance variables
- private String model;
- private int year;
-
- // constructor: set instance variables to default values
- public Car()
- {
- // 1. set the instance variables to default values "" and 2019
-
-
- }
-
- // constructor: set instance variables to init parameters
- public Car(String initModel, int initYear)
- {
- // 2. set the instance variables to the init parameter variables
-
-
- }
-
- // Print Car info
- public void print()
- {
- System.out.println("Car model: " + model);
- System.out.println("Car year: " + year);
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // 3. call the constructor to create 2 new Car objects using the 2 constructors. car1 will be the default values. car2 should be a Honda 2010 car.
- Car car1 =
- Car car2 =
-
- car1.print();
- car2.print();
- }
- }
- ====
- // Test Code for Lesson 5.2.0 - Car
- import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
+ :language: java
+ :autograde: unittest
+ :practice: T
- import java.io.*;
+ The following class defines a Car with the instance variables model and year,
+ for example a Honda 2010 car. However, some of the code is missing. First, fill in
+ the code to create a ``Car`` constructor. Then, fill in the code to call the constructor
+ in the main method to create 2 ``Car`` objects. The first car should be a 2023 Ford and
+ the second car should be a 2010 Honda. Run your program and make sure it works and
+ prints out the information for both cars.
+ ~~~~
+ public class Car
+ {
+ // instance variables
+ private String model;
+ private int year;
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Car model: \nCar year: 2019\nCar model: Honda\nCar year: 2010";
+ // constructor: set instance variables to init parameters
+ public Car(String initModel, int initYear)
+ {
+ // 1. set the instance variables to the init parameter variables
- boolean passed = getResults(expect, output, "Running main");
- assertTrue(passed);
- }
- }
+ }
+
+ // Print Car info
+ public void print()
+ {
+ System.out.println("Car model: " + model);
+ System.out.println("Car year: " + year);
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // 2. Call the constructor to create 2 new Car objects with different
+ // values The first car should be a 2023 Ford and the second car
+ // should be a 2010 Honda.
-Constructors are used to set the initial state of an object by initializing its instance variables. The examples above have instance variables that are primitive types, but you can have other objects, reference types, as instance variables. For example, a Person class could have an Address object as an instance variable, and the Address class could have String instance variables for the street, city, and state.
+ Car car1 =
+ Car car2 =
-(Advanced AP Topic Warning) When you pass object references as parameters to constructors or methods, they become aliases for the original object and can change it. If a constructor has an object instance variable, it can copy the referenced object in the parameter using new and the constructor of the referenced object like below so that it does not change the state of the original object. You will see more examples like this in later lessons.
+ car1.print();
+ car2.print();
+ }
+ }
+ ====
+ // Test Code for Lesson 5.2.0 - Car
+ import static org.junit.Assert.*;
-.. code-block:: java
+ import org.junit.Test;
- public class Person
- {
- private String name;
- private Address addr; //Assumes an Address class is already defined
-
- // constructor: initialize instance variable and call Address constructor to make a copy
- public Person(String initName, Address initAddr)
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
{
- name = initName;
- addr = new Address(initAddr.getStreet(),
- initAddr.getCity(), initAddr.getState());
+ String output = getMethodOutput("main");
+ String expect = "Car model: Ford\nCar year: 2023\nCar model: Honda\nCar year: 2010";
+
+ boolean passed = getResults(expect, output, "Running main");
+ assertTrue(passed);
}
- }
-
+ }
+
+Advanced AP Topic: Reference parameters
+------------------------------------------------
+
+When you pass object references as parameters to
+constructors or methods, those references refer to the same objects as the
+references in the caller. If the objects are immutable, like ``String`` objects
+it doesn’t matter at all. On the other hand, if the objects are **mutable**,
+meaning their instance variables can change after they are constructed, then
+storing the passed-in reference in an instance variable in your object can lead
+to surprising results: if some other code changes the object it will change for
+you too. If that’s not what you want, sometimes it makes sense to copy the
+object passed to the constructor and store the copy in the instance variable
+instead. How to make the copy will depend on the class of the object but often
+you can just construct a new object of the appropriate class using values from
+the original object as shown below.
+
+.. code-block:: java
+
+ public class Person
+ {
+ private String name;
+ private Address addr; // Assumes an Address class is already defined
+
+ // constructor: initialize instance variable and call Address constructor to
+ // make a copy
+ public Person(String initName, Address initAddr)
+ {
+ name = initName;
+ addr =
+ new Address(
+ initAddr.getStreet(),
+ initAddr.getCity(),
+ initAddr.getState());
+ }
+ }
|Groupwork| Programming Challenge : Student Class
--------------------------------------------------
We encourage you to work in pairs for this challenge to create a Student class with constructors.
-1. First, brainstorm in pairs to do the **Object-Oriented Design** for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables?
+1. First, brainstorm in pairs to do the **Object-Oriented Design** for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables?
-2. Write a Student class below that has your 4 instance variables and write at least 3 different constructors: one that has no parameters and initializes the instance variables to default values, one that has 4 parameters to set the instance variables, and one that has 1 parameter for the most important instance variable and uses defaults for the others.
+2. Write a Student class below that has your 4 instance variables and write a constructor that has 4 parameters to set all of the instance variables.
3. Add a print() method that uses System.out.println to print out all the instance variables.
-4. Add a main method that constructs at least 3 Student objects using the 3 different constructors and then calls their print() methods.
+4. Add a main method that constructs at least 2 Student objects using the constructor with different values and then calls their print() methods.
.. activecode:: challenge-5-2-Student-class
:language: java
:autograde: unittest
- Create a class Student with 4 instance variables, 3 constructors, and a print method. Write a main method that creates 3 Student objects with the 3 different constructors and calls their print() method.
- ~~~~
- /** class Student
- * with 4 instance variables,
- * 3 constructors, a print method,
- * and a main method to test them.
+ Create a class Student with 4 instance variables, a constructor, and a print method. Write a main method that creates 2 Student objects with the constructor and calls their print() method.
+ ~~~~
+ /**
+ * class Student with 4 instance variables, a constructor, a print method, and a
+ * main method to test them.
*/
- public class Student
- {
+ public class Student
+ {
// Write 4 instance variables
-
-
- // Write 3 constructors to initialize the instance variables
- // 1. no parameters using default values
- // 2. 1 parameter and the rest default values
- // 3. 4 parameters
-
-
+
+ // Write a constructor with 4 parameters to initialize all of the instance
+ // variables
+
// Write a print method that prints all the instance variables
- public void print()
- {
-
-
- }
-
- // main method
+ public void print() {}
+
+ // main method
public static void main(String[] args)
- {
- // Construct 3 Student objects using the 3 different constructors
-
-
- // call their print() methods
-
+ {
+ // Construct 2 Student objects using the constructor with different values
+
+ // call their print() methods
+
}
- }
+ }
+
====
- // Test Code for Lesson 5.2.1 - Challenge - Student
+ // Test Code for Lesson 5.2.1 - Challenge - Student
import static org.junit.Assert.*;
- import org.junit.After;
- import org.junit.Before;
+
import org.junit.Test;
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("Student");
- Object[] values = new Object[]{"Name", 0};
+ Object[] values = new Object[] {"Name", 0};
setDefaultValues(values);
}
@Test
- public void testDefaultConstructor()
+ public void testCallConstructors()
{
- String output = checkDefaultConstructor();
- String expect = "pass";
+ String code = getCodeWithoutComments();
+ String search = "= new Student(";
- boolean passed = getResults(expect, output, "Checking default constructor");
+ int num = countOccurences(code, search);
+
+ String expect = search + "...) x 2";
+ String actual = search + "...) x " + num;
+
+ boolean passed = getResults(expect, actual, "Checking that you made 2 Student objects");
assertTrue(passed);
}
@Test
- public void testConstructor4()
+ public void testConstructors()
{
- String output = checkConstructor(4);
- String expect = "pass";
+ String code = getCodeWithoutComments();
+ String search = "public Student(";
+
+ int num = countOccurences(code, search);
+
+ String expect = search + "...) x 1";
+ String actual = search + "...) x " + num;
- boolean passed = getResults(expect, output, "Checking constructor with 4 parameters");
+ boolean passed = getResults(expect, actual, "Checking that you made a constructor");
assertTrue(passed);
}
@Test
- public void testConstructor1()
+ public void testPrint()
{
- String output = checkConstructor(1);
- String expect = "pass";
+ String code = getCodeWithoutComments();
+ String search = ".print()";
+
+ int num = countOccurences(code, search);
- boolean passed = getResults(expect, output, "Checking constructor with 1 parameter");
+ String expect = search + " x 2";
+ String actual = search + " x " + num;
+
+ boolean passed = getResults(expect, actual, "Checking that you called print 2 times");
assertTrue(passed);
}
@@ -400,55 +485,146 @@ We encourage you to work in pairs for this challenge to create a Student class w
String expect = "4 Private";
String output = testPrivateInstanceVariables();
- boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)");
+ boolean passed = getResults(expect, output, "Checking for 4 Private Instance Variable(s)");
assertTrue(passed);
}
+ }
- @Test
- public void testPrint()
- {
- String output = getMethodOutput("print");
- String expect = "More than 15 characters";
- String actual = " than 15 characters";
-
- if (output.length() < 15) {
- actual = "Less" + actual;
- } else {
- actual = "More" + actual;
- }
- boolean passed = getResults(expect, actual, "Checking print method");
- assertTrue(passed);
- }
+|Groupwork| Design a Class for your Community
+----------------------------------------------------------
+.. |community5.1| raw:: html
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");//.split("\n");
- String expect = "3+ line(s) of text";
- String actual = " line(s) of text";
- int len = output.split("\n").length;
-
- if (output.length() > 0) {
- actual = len + actual;
- } else {
- actual = output.length() + actual;
- }
- boolean passed = len >= 3;
+ Lesson 5.1 Community Challenge
+
+In the last lesson, you came up with a class of your own choice relevant to you or your community. In this lesson, you will add a constructor to this class.
+
+1. Consult your completed worksheet or your code in |community5.1| for the class name and its 3 instance variables that you created. Copy them into the active code exercise below.
+
+2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters.
+
+3. Write a print() method that uses System.out.println to print out all the instance variables.
+
+4. Write a main method that constructs at least 2 objects of your class using the constructor and then calls their print() methods.
+
+.. activecode:: community-challenge-5-2
+ :language: java
+ :autograde: unittest
+
+ Copy your class with its 3 instance variables from |community5.1|. Add a constructor with 3 parameters to set all of the instance variables to the given parameters. Write a print() method that uses System.out.println to print out all the instance variables. Write a main method that constructs at least 2 objects of your class using the constructors and then calls their print() methods.
+ ~~~~
+ public class // Add your class name here!
+ {
+ // 1. copy in your instance variables for class from the last lesson
+
+ // 2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters.
+
+
+ // 3. Write a print() method that uses System.out.println to print out all the instance variables.
+
+ // 4. Write a main method that constructs at least 2 objects of your class
+ // using the constructor and then calls their print() methods.
+ public static void main(String[] args)
+ {
+ // Construct 2 objects of your class to test the constructors
+
+
+ // call the objects print() methods
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "3 Private";
+ String output = testPrivateInstanceVariables();
+ boolean passed = false;
+ if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1)))
+ passed = true;
+ passed = getResults(expect, output, "Checking private instance variable(s)", passed);
+ assertTrue(passed);
+ }
+
+ /* No longer required
+ @Test
+ public void testDefaultConstructor()
+ {
+ String output = checkDefaultConstructor();
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking default constructor");
+ assertTrue(passed);
+ }
+ */
+
+ @Test
+ public void testConstructor3()
+ {
+ String output = checkConstructor(3);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking constructor with 3 parameters");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrint()
+ {
+ String output = getMethodOutput("print");
+ String expect = "More than 15 characters";
+ String actual = " than 15 characters";
+
+ if (output.length() < 15)
+ {
+ actual = "Less" + actual;
+ }
+ else
+ {
+ actual = "More" + actual;
+ }
+ boolean passed = getResults(expect, actual, "Checking print method");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main"); // .split("\n");
+ String expect = "3+ line(s) of text";
+ String actual = " line(s) of text";
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 3;
+
+ getResults(expect, actual, "Checking output", passed);
+ assertTrue(passed);
+ }
+ }
- getResults(expect, actual, "Checking output", passed);
- assertTrue(passed);
- }
- }
-
-
Summary
--------
- **Constructors** are used to set the initial state of an object, which includes initial values for all instance variables.
-- When no constructor is written, Java provides a no-argument **default constructor**, and the instance variables are set to their default values (0 for int and double, null for objects like String).
+- When no constructor is written, Java provides a no-argument **default constructor**, and the instance variables are set to their default values (0 for ``int`` and ``double``, ``null`` for objects like ``String``).
- Constructor parameters are local variables to the constructor and provide data to initialize instance variables.
@@ -463,7 +639,7 @@ AP Practice
:practice: T
Consider the definition of the Cat class below. The class uses the instance variable isSenior to indicate whether a cat is old enough to be considered a senior cat or not.
-
+
.. code-block:: java
public class Cat
@@ -471,6 +647,7 @@ AP Practice
private String name;
private int age;
private boolean isSenior;
+
public Cat(String n, int a)
{
name = n;
@@ -487,23 +664,23 @@ AP Practice
}
Which of the following statements will create a Cat object that represents a cat that is considered a senior cat?
-
+
- Cat c = new Cat ("Oliver", 7);
- The age 7 is less than 10, so this cat would not be considered a senior cat.
-
+
- Cat c = new Cat ("Max", "15");
- An integer should be passed in as the second parameter, not a string.
-
+
- Cat c = new Cat ("Spots", true);
- An integer should be passed in as the second parameter, not a boolean.
-
+
- Cat c = new Cat ("Whiskers", 10);
+ Correct!
-
+
- Cat c = new Cat ("Bella", isSenior);
- An integer should be passed in as the second parameter and isSenior would be undefined outside of the class.
@@ -526,7 +703,7 @@ AP Practice
:feedback_e: Option II will create a cat that is 0 years old with 5 kittens.
Consider the following class definition. Each object of the class Cat will store the cat’s name as name, the cat’s age as age, and the number of kittens the cat has as kittens. Which of the following code segments, found in a class other than Cat, can be used to create a cat that is 5 years old with no kittens?
-
+
.. code-block:: java
public class Cat
@@ -553,12 +730,12 @@ AP Practice
I. Cat c = new Cat("Sprinkles", 5, 0);
II. Cat c = new Cat("Lucy", 0, 5);
III. Cat c = new Cat("Luna", 5);
-
+
.. mchoice:: AP5-2-3
:practice: T
Consider the following class definition.
-
+
.. code-block:: java
public class Cat
@@ -569,13 +746,13 @@ AP Practice
}
The following statement appears in a method in a class other than Cat. It is intended to create a new Cat object c with its attributes set to "black" and true. Which of the following can be used to replace **missing constructor code** in the class definition so that the object c below is correctly created?
-
+
.. code-block:: java
-
+
Cat c = new Cat("black", true);
-
+
- .. code-block:: java
-
+
public Cat(String c, boolean h)
{
c = "black";
@@ -585,7 +762,7 @@ AP Practice
- The constructor should be changing the instance variables, not the local variables.
- .. code-block:: java
-
+
public Cat(String c, boolean h)
{
c = "black";
@@ -595,7 +772,7 @@ AP Practice
- The constructor should be changing the instance variables, not the local variables.
- .. code-block:: java
-
+
public Cat(String c, boolean h)
{
c = color;
@@ -605,7 +782,7 @@ AP Practice
- The constructor should be changing the instance variables, not the local variables.
- .. code-block:: java
-
+
public Cat(String c, boolean h)
{
color = black;
@@ -615,7 +792,7 @@ AP Practice
- The constructor should be using the local variables to set the instance variables.
- .. code-block:: java
-
+
public Cat(String c, boolean h)
{
color = c;
@@ -623,4 +800,3 @@ AP Practice
}
+ Correct!
-
diff --git a/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst b/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst
index 8480b8043..fcbf933b8 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-3-comments-conditions.rst
@@ -1,25 +1,11 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-3-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
+|Time45|
+
Comments and Conditions
=======================
@@ -45,10 +31,10 @@ There are 3 types of comments in Java:
.. |String class| raw:: html
String class
-
-The special characters ``//`` are used to mark the rest of the line as a comment in many programming languages. If the comment is going to be multiple lines, we use ``/*`` to start the comment and ``*/`` to end the comment.
-There is also a special version of the multi-line comment, ``/**`` ``*/``, called the documentation comment. Java has a cool tool called |javadoc| that comes with the |Java JDK| that will pull out all of these comments to make documentation of a class as a web page. This tool generates the official Java documentation too, for example for the |String class|. Although you do not have to use this in the AP exam, it's a good idea to use the documentation comment in front of classes, methods, and instance variables in case you want ot use this tool.
+The special characters ``//`` are used to mark the rest of the line as a comment in many programming languages. If the comment is going to be multiple lines, we use ``/*`` to start the comment and ``*/`` to end the comment.
+
+There is also a special version of the multi-line comment, ``/**`` ``*/``, called the documentation comment. Java has a cool tool called |javadoc| that comes with the |Java JDK| that will pull out all of these comments to make documentation of a class as a web page. This tool generates the official Java documentation too, for example for the |String class|. Although you do not have to use this in the AP exam, it's a good idea to use the documentation comment in front of classes, methods, and instance variables in case you want to use this tool.
|Exercise| **Check your understanding**
@@ -57,21 +43,21 @@ There is also a special version of the multi-line comment, ``/**`` ``*/``, call
:match_1: single-line comment|||//
:match_2: multi-line comment|||/* */
:match_3: Java documentation comment|||/** */
-
+
Drag the definition from the left and drop it on the correct symbols on the right. Click the "Check Me" button to see if you are correct.
-
+
The compiler will skip over comments, and they don't affect how your program runs. They are for you, your teacher, and other programmers working with you. Here are some examples of good commenting:
-.. code-block:: java
+.. code-block:: java
/**
* MyClass.java
* @author My Name
- * @since Date
+ * @since Date
* This class keeps track of the max score.
- */
- public class MyClass()
+ */
+ public class MyClass()
{
private int max = 10; // this keeps track of the max score
/* The print() method prints out the max */
@@ -83,28 +69,28 @@ Notice that there are some special tags that you can use in Java documentation.
- @author Author of the program
- @since Date released
-- @version Version of program
+- @version Version of program
- @param Parameter of a method
- @return Return value for a method
-
+
Preconditions and Postconditions
---------------------------------
As you write methods in a class, it is a good idea to keep in mind the **preconditions** and the **postconditions** for the method and write them in the comments. A precondition is a condition that must be true for your method code to work, for example the assumption that the parameters have values and are not null. The methods could check for these preconditions, but they do not have to. The precondition is what the method expects in order to do its job properly.
-A postcondition is a condition that is true after running the method. It is what the method promises to do. Postconditions describe the outcome of running the method, for example what is being returned or the changes to the instance variables. These assumptions are very useful to other programmers who want to use your class and get the correct results.
+A postcondition is a condition that is true after running the method. It is what the method promises to do. Postconditions describe the outcome of running the method, for example what is being returned or the changes to the instance variables. These assumptions are very useful to other programmers who want to use your class and get the correct results.
Here is an example of preconditions, postconditions, and @param in the Turtle code that we have used in the past for our drawing turtles.
-.. code-block:: java
+.. code-block:: java
/**
* Constructor that takes the x and y position for the
* turtle
- * Preconditions: parameters x and y are coordinates from 0 to
+ * Preconditions: parameters x and y are coordinates from 0 to
* the width and height of the world.
- * Postconditions: the turtle is placed in (x,y) coordinates
+ * Postconditions: the turtle is placed in (x,y) coordinates
* @param x the x position to place the turtle
* @param y the y position to place the turtle
*/
@@ -113,41 +99,60 @@ Here is an example of preconditions, postconditions, and @param in the Turtle co
xPos = x;
yPos = y;
}
-
+
|CodingEx| **Coding Exercise**
Try to break the preconditions of the Turtle constructor below. Does the Turtle constructor behave properly if you break the preconditions that x and y are between 0 and 300. Try giving the Turtle constructor x and y values out of these ranges. What happens? Does the method give good results? Does it give any warnings? What about the t.forward() method? Does it have any preconditions that you can break?
-.. |github| raw:: html
-
- here
-
-.. |repl link| raw:: html
-
- repl.it link
-
-(If the code below does not work for you, you can copy the code into this |repl link| (refresh page after forking and if it gets stuck) or download the files |github| to use in your own IDE.)
-
.. activecode:: turtle-preconditions
:language: java
+ :autograde: unittest
:datafile: turtleClasses.jar
- import java.util.*;
+ Try to break the preconditions about the range of the values of x and y in the Turtle constructor below.
+ ~~~~
import java.awt.*;
+ import java.util.*;
public class TurtlePreconditions
{
- public static void main(String[] args)
- {
- World world = new World(300,300);
- // Change 0,0 to other values outside of 0-300 to break the preconditions and see what happens
- Turtle t = new Turtle(0,0,world);
- t.turnRight();
- world.show(true);
- }
+ public static void main(String[] args)
+ {
+ World world = new World(300, 300);
+ // Change 0, 0 in the Turtle constructor to other values
+ // outside of 0-300 to break the preconditions
+ // and see what happens
+ Turtle t = new Turtle(0, 0, world);
+ t.turnRight();
+ world.show(true);
+ }
}
-
-The Turtle constructor's precondition is that x and y should be between 0 and the width and height of the world. If it receives values out of this range, it sets x and y to the closest legal values that it can so that the turtle appears just at the edge of the world. Similarly, the forward() method will not allow the turtle to leave the world.
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("TurtlePreconditions");
+ }
+
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ boolean passed = !(code.contains("new Turtle(0, 0"));
+ passed = getResults("true", "" + passed, "Change (0, 0) to try to break preconditions", passed);
+ assertTrue(passed);
+ }
+ }
+
+The Turtle constructor's precondition is that x and y should be between 0 and the width and height of the world. If it receives values out of this range, it sets x and y to the closest legal values that it can so that the turtle appears just at the edge of the world. Similarly, the forward() method will not allow the turtle to leave the world.
|Exercise| **Check your understanding**
@@ -162,9 +167,9 @@ The Turtle constructor's precondition is that x and y should be between 0 and th
:feedback_a: It is not reasonable the s which sets the score should be negative.
:feedback_b: The precondition should be about the parameters of the constructor. score is not the parameter variable.
:feedback_c: Correct. It is reasonable that the score and extraCredit should be set to positive values using the parameters s and ec.
- :feedback_d: Correct. It is reasonable that the parameter n which sets the name should be not empty.
+ :feedback_d: Correct. It is reasonable that the parameter n which sets the name should be not empty.
:feedback_e: The precondition should be about the parameters of the constructor. score is not the parameter variable.
-
+
Consider the following class definition.
.. code-block:: java
@@ -185,9 +190,9 @@ The Turtle constructor's precondition is that x and y should be between 0 and th
}
Which of the following preconditions are reasonable for the TestScore constructor?
-
-Let's consider the substring method in Java. This method has a strong precondition that its arguments refer to indices within the given string.
+
+Let's consider the substring method in Java. This method has a strong precondition that its arguments refer to indices within the given string.
|CodingEx| **Coding Exercise**
@@ -199,21 +204,25 @@ Let's consider the substring method in Java. This method has a strong preconditi
~~~~
public class SubstringPreconditions
{
- public static void main(String[] args)
- {
- String str = "hello";
- System.out.println( str.substring(-1,10) );
- }
+ public static void main(String[] args)
+ {
+ String str = "hello";
+ System.out.println(str.substring(-1, 10));
+ }
}
+
====
// Test for Lesson 5.3.2 Substring-preconditions
import static org.junit.Assert.*;
+
import org.junit.*;
+
import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
- public RunestoneTests() {
+ public RunestoneTests()
+ {
super("SubstringPreconditions");
}
@@ -228,9 +237,9 @@ Let's consider the substring method in Java. This method has a strong preconditi
}
.. note::
-
+
The method str.substring(beginIndex, endIndex) has the precondition that 0 <= beginIndex <= endIndex <= str.length.
-
+
|Exercise| **Check your understanding**
.. mchoice:: AP5-3-2
@@ -241,10 +250,10 @@ Let's consider the substring method in Java. This method has a strong preconditi
:answer_d: /* Precondition: 0 <= i < str.length() */
:correct: d
:feedback_a: This is true but it could still throw an exception if i is a large value.
- :feedback_b: This is true but it could still throw an exception if i is a negative value.
+ :feedback_b: This is true but it could still throw an exception if i is a negative value.
:feedback_c: This is true but a little too restrictive.
:feedback_d: Correct. i can refer to character 0 up to str.length().
-
+
The following method is intended to return the substring starting at index i until the end of the string. For example, getiToEnd("012",1) should return "12". Which of the following is the most appropriate precondition for the method so that it does not throw an exception?
.. code-block:: java
@@ -254,7 +263,7 @@ Let's consider the substring method in Java. This method has a strong preconditi
{
return str.substring(i, str.length());
}
-
+
@@ -262,9 +271,9 @@ Let's consider the substring method in Java. This method has a strong preconditi
Software Validity and Use-Case Diagrams
----------------------------------------
-Preconditions and postconditions are covered on the AP CS A exam. Software validity, testing, and use-case diagrams which are discussed in this subsection are not covered on the AP CS A exam, but they are described here because they use preconditions and postconditions and are used by professional programmers.
+Preconditions and postconditions are covered on the AP CSA exam. Software validity, testing, and use-case diagrams which are discussed in this subsection are not covered on the AP CSA exam, but they are described here because they use preconditions and postconditions and are used by professional programmers.
-Determining the preconditions and postconditions help us to test our code and determine the **validity** of our software. Software validity tests whether the software does what it is supposed to do before it is released. This is sometimes very important. For example, if the code is part of a satellite going to outerspace or is going to be used in an emergency condition, we want to test it thoroughly and make sure it works and is valid before it is put into use.
+Determining the preconditions and postconditions help us to test our code and determine the **validity** of our software. Software validity tests whether the software does what it is supposed to do before it is released. This is sometimes very important. For example, if the code is part of a satellite going to outerspace or is going to be used in an emergency condition, we want to test it thoroughly and make sure it works and is valid before it is put into use.
Good software testers actually try to break the code! They try all kinds of input to see what the software will do because you never know what users will try or what conditions there will be. So, always think what the preconditions of your code are and see what happens when you break them, and then see if you can protect or warn against that.
@@ -277,7 +286,7 @@ Preconditions and postconditions can also help us to design better software syst
:figclass: align-center
Figure 1: Use-Case Diagram of a Restaurant System
-
+
After drawing a Use-Case Diagram, designers write down the preconditions and the postconditions for each Use-Case. Often the successful post-condition for one use-case becomes the preconditions for the next use-case. For example, for the "Order Food" and "Eat Food" Use Cases:
- Preconditions for "Order Food": Customer enters restaurant. Staff is ready to take the order.
@@ -289,7 +298,7 @@ After drawing a Use-Case Diagram, designers write down the preconditions and the
.. shortanswer:: payconditions
- What are the preconditions and postconditions of the use-case "Pay for food"? Remember that these are often related to the other use-case conditions "order food" and "eat food".
+ What are the preconditions and postconditions of the use-case "Pay for food"? Remember that these are often related to the other use-case conditions "order food" and "eat food".
Agile Software Development
----------------------------
@@ -302,7 +311,7 @@ There are many different models for software development. The **waterfall model*
:align: center
:figclass: align-center
- Figure 2: Waterfall vs Agile Models
+ Figure 2: Waterfall vs Agile Models
One very popular type of agile development is called **Scrum**. The following short |video| describes software development with Scrum.
@@ -312,8 +321,8 @@ One very popular type of agile development is called **Scrum**. The following sh
.. youtube:: TRcReyRYIMg
- :height: 315
- :width: 560
+ :height: 400
+ :width: 600
:align: left
|Groupwork| Group Exercise
@@ -330,15 +339,15 @@ Try the |pogil game| in groups to practice the iterative and incremental agile d
.. |Creately.com| raw:: html
- Creately.com
+ Creately.com
Working in pairs or groups, come up with 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step. You could pretend to buy something online to come up with the steps. (You could use an online drawing tool like |Creately.com| (choose Use-Case Diagrams) to draw a Use-Case diagram for the Online Store System, but it is not required). Don't forget to list the preconditions and postconditions for each step. You can type in your answer below.
.. shortanswer:: challenge-5-3-use-case-preconditions
Write down 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step.
-
-
+
+
Here is a simple class called User that could be used in an online store. Add good commenting to this code before the class, the instance variables, and the methods.
.. activecode:: challenge-5-3-comments
@@ -348,51 +357,51 @@ Here is a simple class called User that could be used in an online store. Add go
// comments?
public class User
{
-
- private String username;
- private String password;
-
- public User()
- {
- username = "guest";
- password = "guest" + (int)(Math.random()*1000);
- }
-
- public User(String nameInit, String pwordInit)
- {
- username = nameInit;
- password = pwordInit;
- }
-
- public void welcome()
- {
- System.out.println("Welcome " + username + "!");
- }
-
- public static void main(String[] args)
- {
- User u1 = new User(); // guest login
- // new user
- User u2 = new User("cooldude@gmail.com", "Coolness*10");
- u1.welcome();
- u2.welcome();
- }
+
+ private String username;
+ private String password;
+
+ public User()
+ {
+ username = "guest";
+ password = "guest" + (int) (Math.random() * 1000);
+ }
+
+ public User(String nameInit, String pwordInit)
+ {
+ username = nameInit;
+ password = pwordInit;
+ }
+
+ public void welcome()
+ {
+ System.out.println("Welcome " + username + "!");
+ }
+
+ public static void main(String[] args)
+ {
+ User u1 = new User(); // guest login
+ // new user
+ User u2 = new User("cooldude@gmail.com", "Coolness*10");
+ u1.welcome();
+ u2.welcome();
+ }
}
+
====
// Test for 5.3.5 Comments
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- import java.nio.file.Files;
- import java.nio.file.Paths;
+ import org.junit.*;
+
+ import java.io.*;
public class RunestoneTests extends CodeTestHelper
{
private String program;
@Test
- public void testMain() throws IOException
+ public void testMain()
{
String output = getMethodOutput("main");
String expect = "Welcome guest!\nWelcome cooldude@gmail.com!";
@@ -401,15 +410,15 @@ Here is a simple class called User that could be used in an online store. Add go
}
@Test
- public void testClassComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testClassComment()
+ {
+ program = getCodeWithComments();
int index = program.indexOf("public class User");
- String beginning = program.substring(0, index-1).trim();
+ String beginning = program.substring(0, index - 1).trim();
String expected = "A comment starting with // or /* and not // comments?";
- //System.out.println(beginning);
+ // System.out.println(beginning);
boolean pass = !beginning.startsWith("// comments") && isComment(beginning);
@@ -418,41 +427,42 @@ Here is a simple class called User that could be used in an online store. Add go
}
@Test
- public void testVariablesComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testVariablesComment()
+ {
+ program = getCodeWithComments();
int start = program.indexOf("{") + 1;
int end = program.indexOf("private String username");
String comment = program.substring(start, end).trim();
String expected = "A comment starting with // or /*";
- //System.out.println(beginning);
+ // System.out.println(beginning);
boolean passed = getResults(expected, comment, "Variable comment", isComment(comment));
assertTrue(passed);
}
@Test
- public void testDefaultConstructorComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testDefaultConstructorComment()
+ {
+ program = getCodeWithComments();
int start = program.indexOf("password;") + "password;".length() + 1;
int end = program.indexOf("public User()");
String comment = program.substring(start, end).trim();
String expected = "A comment starting with // or /*";
- //System.out.println(beginning);
+ // System.out.println(beginning);
- boolean passed = getResults(expected, comment, "Default constructor comment", isComment(comment));
+ boolean passed =
+ getResults(expected, comment, "Default constructor comment", isComment(comment));
assertTrue(passed);
}
@Test
- public void testConstructorComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testConstructorComment()
+ {
+ program = getCodeWithComments();
int start = program.indexOf("*1000);");
start = program.indexOf("}", start) + 1;
@@ -460,16 +470,16 @@ Here is a simple class called User that could be used in an online store. Add go
String comment = program.substring(start, end).trim();
String expected = "A comment starting with // or /*";
- //System.out.println(beginning);
+ // System.out.println(beginning);
boolean passed = getResults(expected, comment, "Constructor comment", isComment(comment));
assertTrue(passed);
}
@Test
- public void testWelcomeComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testWelcomeComment()
+ {
+ program = getCodeWithComments();
int start = program.indexOf("password = pwordInit;");
start = program.indexOf("}", start) + 1;
@@ -477,16 +487,17 @@ Here is a simple class called User that could be used in an online store. Add go
String comment = program.substring(start, end).trim();
String expected = "A comment starting with // or /*";
- //System.out.println(beginning);
+ // System.out.println(beginning);
- boolean passed = getResults(expected, comment, "Welcome method comment", isComment(comment));
+ boolean passed =
+ getResults(expected, comment, "Welcome method comment", isComment(comment));
assertTrue(passed);
}
@Test
- public void testMainComment() throws IOException {
- //System.out.println(program);
- program = new String(Files.readAllBytes(Paths.get("User.java")));
+ public void testMainComment()
+ {
+ program = getCodeWithComments();
int start = program.indexOf("username + \"!\");");
start = program.indexOf("}", start) + 1;
@@ -494,23 +505,20 @@ Here is a simple class called User that could be used in an online store. Add go
String comment = program.substring(start, end).trim();
String expected = "A comment starting with // or /*";
- //System.out.println(beginning);
+ // System.out.println(beginning);
boolean passed = getResults(expected, comment, "Main method comment", isComment(comment));
assertTrue(passed);
}
- private boolean isComment(String block) {
- if (!block.contains("\n") && block.startsWith("//"))
- return true;
- if (block.startsWith("/*") && block.endsWith("*/"))
- return true;
+ private boolean isComment(String block)
+ {
+ if (!block.contains("\n") && block.startsWith("//")) return true;
+ if (block.startsWith("/*") && block.endsWith("*/")) return true;
return false;
-
}
}
-
Summary
-------
diff --git a/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst
index d240a508a..118331434 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-4-accessor-methods.rst
@@ -1,31 +1,26 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-4-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
-Accessor Methods
-=================
-
-Since the instance variables in a class are usually marked as private to the class, programmers provide public methods that allow safe access to the instance variable values in a class. **Accessor methods**, also called **get methods** or **getters**, allow a way to get the value of each instance variable from outside of the class. In the next lesson, we will see **mutator methods**, also called **set methods** or **setters**, that allow a way to change the values of the instance variables. In Unit 2, we also used set/get methods with the Turtle class to get the Turtle object's width, height, xPosition, etc. or to change them.
-
-If you used a language like App Inventor in an AP CSP class, you may have used setter and getter blocks. In App Inventor, you cannot make your own classes, but you can declare UI objects like Button1, Button2 from the Button class and use their get/set methods for any property like below.
+|Time45|
+
+Accessors / Getters
+===================
+
+Since the instance variables in a class are usually marked as ``private`` to the
+class, if you want code outside the class to be able to access the value of an
+instance variable, you need to write what is formally called an **accessor
+methods** but which everyone actually just calls a **getter**. A getter is a
+``public`` method that takes no arguments and returns the value of the
+``private`` instance variable. (We discussed using getters in section 2.5.)
+
+If you used a language like App Inventor in an AP CSP class, you may have used
+setter and getter blocks. In App Inventor, you cannot make your own classes, but
+you can declare UI objects like Button1, Button2 from the Button class and use
+their get/set methods for any property like below. (We'll talk about setters in
+Java in the next section.)
.. figure:: Figures/AppInvSetGet.png
:width: 300px
@@ -33,62 +28,89 @@ If you used a language like App Inventor in an AP CSP class, you may have used s
:figclass: align-center
Figure 1: App Inventor Set and Get blocks for object Button1
-
-Java programmers write get methods for each instance variable that look like the following. Notice that the get method returns the instance variable's value and it has a return type that is the same type as the variable that it is returning.
+
+You don't need to write a getter for every instance variable in a class but if
+you want code outside the class to be able to get the value of one of your
+instance variables, you'll need to write a getter that looks like the following.
.. code-block:: java
- class ExampleTemplate {
-
- //Instance variable declaration
- private typeOfVar varName;
-
- // Accessor (getter) method template
- public typeOfVar getVarName()
- {
- return varName;
- }
-
+ class ExampleTemplate
+ {
+
+ // Instance variable declaration
+ private typeOfVar varName;
+
+ // Accessor (getter) method template
+ public typeOfVar getVarName()
+ {
+ return varName;
+ }
}
-Here's an example of an accessor method called getName() for the Student class which also demonstrates how to call getName() using a Student object:
+Notice that the getter’s return type is the same as the type of the instance
+variable and all the body of the getter does is return the value of the variable
+using a ``return`` statement. (We'll talk more about the ``return`` statement in
+section 5.6 but for now just notice that it is followed by an expression whose
+value must be the same type as the return type in the method's header. In a
+getter that will definitely be true as long as the type of the instance variable
+and the return type of the getter are the same.)
+
+Here's an example of an accessor method called ``getName`` for the ``Student``
+class which also demonstrates how to call ``getName`` using a ``Student``
+object:
.. code-block:: java
- class Student {
-
+ class Student
+ {
+
//Instance variable name
private String name;
-
+
/** getName() example
* @return name */
public String getName()
{
return name;
}
-
+
public static void main(String[] args)
- {
+ {
// To call a get method, use objectName.getVarName()
Student s = new Student();
System.out.println("Name: " + s.getName() );
}
+Note, that getters only return the *value* of the variable. In other words, the
+code that called the getter and which receives that value has no ability to
+change the object's instance variable; they just get a copy of the value.
+However if the instance variable is a reference type like ``String`` or
+``Person`` the value that is copied is the value of the reference. That means
+the caller receives a new copy of the reference that points to the same object
+as is stored in the instance variable. In the next section, when we talk about
+mutation, you'll see how that means that the caller might be able to change the
+object even though it can't change the reference.
+
.. note::
- Some common errors with methods that return values are:
-
- - Forgetting a return type like int before the method name.
- - Forgetting to use the return keyword to return a value at the end of the method.
- - Forgetting to do something with the value returned from a method (like saving it into a variable or printing it out).
-
-
+ Some common errors when writing and using getters are:
+
+ - Forgetting a return type like ``int`` before the method name.
+
+ - Forgetting to use the ``return`` keyword to return a value at the end of
+ the method.
+
+ - Forgetting to do something with the value returned from a method, like
+ assigning it to a variable or printing it out.
+
+
.. |Java visualizer1| raw:: html
Java visualizer
-
-Try the following code. Note that this active code window has 2 classes! The main method is in a separate **Tester** or **Driver** class. It does not have access to the private instance variables in the other Student class. Note that when you use multiple classes in an IDE, you usually put them in separate files, and you give the files the same name as the public class in them. In active code and IDEs, you can put 2 classes in 1 file, as demonstrated here, but only 1 of them can be public and have a main method in it. You can also view the fixed code in the |Java visualizer1|.
-
+
+Try the following code. Note that this active code window has 2 classes! The main method is in a separate **Tester** or **Driver** class. It does not have access to the private instance variables in the other Student class. Note that when you use multiple classes in an IDE, you usually put them in separate files, and you give the files the same name as the public class in them. In active code and IDEs, you can put 2 classes in 1 file, as demonstrated here, but only 1 of them can be public and have a main method in it. You can also view the fixed code in the |Java visualizer1|.
+
|CodingEx| **Coding Exercise**
@@ -99,92 +121,97 @@ Try the following code. Note that this active code window has 2 classes! The mai
Try the following code. Note that it has a bug! It tries to access the private instance variable email from outside the class Student. Change the main method in Tester class so that it uses the appropriate public accessor method (get method) to access the email value instead.
~~~~
- public class TesterClass
+ public class TesterClass
{
- // main method for testing
- public static void main(String[] args)
- {
- Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
- System.out.println("Name:" + s1.getName() );
- // Fix the bug here!
- System.out.println("Email:" + s1.email );
- System.out.println("ID: " + s1.getId() );
- }
- }
+ // main method for testing
+ public static void main(String[] args)
+ {
+ Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
+ System.out.println("Name:" + s1.getName());
+ // Fix the bug here!
+ System.out.println("Email:" + s1.email);
+ System.out.println("ID: " + s1.getId());
+ }
+ }
+
/** Class Student keeps track of name, email, and id of a Student. */
- class Student
+ class Student
{
- private String name;
- private String email;
- private int id;
-
- public Student(String initName, String initEmail, int initId)
- {
- name = initName;
- email = initEmail;
- id = initId;
- }
-
- // accessor methods - getters
- /** getName() @return name */
- public String getName()
- {
- return name;
- }
- /** getEmail() @return email */
- public String getEmail()
- {
- return email;
- }
- /** getName() @return id */
- public int getId()
- {
- return id;
- }
+ private String name;
+ private String email;
+ private int id;
+
+ public Student(String initName, String initEmail, int initId)
+ {
+ name = initName;
+ email = initEmail;
+ id = initId;
+ }
+
+ // accessor methods - getters
+ /** getName() @return name */
+ public String getName()
+ {
+ return name;
+ }
+
+ /** getEmail() @return email */
+ public String getEmail()
+ {
+ return email;
+ }
+
+ /** getName() @return id */
+ public int getId()
+ {
+ return id;
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Name:Skyler\nEmail:skyler@sky.com\nID: 123456";
- boolean passed = getResults(expect, output, "Checking for expected output");
- assertTrue(passed);
- }
-
- @Test
- public void testMethodCall() throws IOException
- {
- String target = "s1.getEmail()";
- boolean passed = checkCodeContains("call to accessor method for email", target);
- assertTrue(passed);
- }
- }
-
+ import org.junit.*;
-There is a subtle difference in methods that return primitive types versus reference/object types. If the method is returning a primitive type like int, it returns a copy of the value. This is called **return by value**. This means the original value is not changed and it is a safe way to access the instance variables.
+ import java.io.*;
-However, object variables really hold a reference to the object in memory. This is not the actual value, but its address in memory. So, if the method is returning an object like String, Java returns a copy of the object reference, not the value itself. Java was especially designed this way because objects tend to be large and we want to avoid copying large objects, so we just pass around references to the objects (their addresses in memory). So, when we call getName(), we actually get back a reference to the String for the name in memory.
-
-toString()
-----------
-
-.. |Java visualizer| raw:: html
-
- Java visualizer
-
-Another common method that returns a value is the toString() method which returns a String description of the instance variables of the object.
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Name:Skyler\nEmail:skyler@sky.com\nID: 123456";
+ boolean passed = getResults(expect, output, "Checking for expected output");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMethodCall() throws IOException
+ {
+ String target = "s1.getEmail()";
+ boolean passed = checkCodeContains("call to accessor method for email", target);
+ assertTrue(passed);
+ }
+ }
-This method is called automatically to try to convert an object to a String when it is needed, for example in a print statement.
+``toString``
+------------
-Here is the Student class again, but this time with a toString() method. Note that when we call System.out.println(s1); it will automatically call the toString() method to cast the object into a String. The toString() method will return a String that is then printed out. Watch how the control moves to the toString() method and then comes back to main in the |Java visualizer| or by using the Code Lens button.
+While not strictly speaking a getter, another important method that returns a
+value is the ``toString`` method. This method is called automatically by Java in
+a number of situations when it needs to convert an object to a ``String``. Most
+notably the methods ``System.out.print`` and ``System.out.println`` use it to
+convert a object argument into a ``String`` to be printed and when objects are
+added to ``String``\ s with ``+`` and ``+=`` their ``String`` representation
+comes from calling their ``toString`` method.
+
+Here is the ``Student`` class again, but this time with a ``toString`` method.
+Note that when we call ``System.out.println(s1)`` it will automatically call the
+``toString`` method to get a ``String`` representation of the ``Student``
+object. The ``toString`` method will return a ``String`` that is then printed out.
+Watch how the control moves to the ``toString`` method and then comes back to ``main``
+in the Java visualizer by using the Show CodeLens button.
.. activecode:: StudentToString
:language: java
@@ -192,53 +219,55 @@ Here is the Student class again, but this time with a toString() method. Note th
See the toString() method in action.
~~~~
- public class TesterClass
+ public class TesterClass
{
- // main method for testing
- public static void main(String[] args)
- {
- Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
- System.out.println(s1);
- }
- }
-
- class Student
+ // main method for testing
+ public static void main(String[] args)
+ {
+ Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
+ System.out.println(s1);
+ }
+ }
+
+ class Student
{
- private String name;
- private String email;
- private int id;
-
- public Student(String initName, String initEmail, int initId)
- {
- name = initName;
- email = initEmail;
- id = initId;
- }
-
- // toString() method
- public String toString()
- {
- return id + ": " + name + ", " + email;
- }
+ private String name;
+ private String email;
+ private int id;
+
+ public Student(String initName, String initEmail, int initId)
+ {
+ name = initName;
+ email = initEmail;
+ id = initId;
+ }
+
+ // toString() method
+ public String toString()
+ {
+ return id + ": " + name + ", " + email;
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "123456: Skyler, skyler@sky.com";
- boolean passed = getResults(expect, output, "Checking for expected output", true);
- assertTrue(passed);
- }
- }
-
-
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "123456: Skyler, skyler@sky.com";
+ boolean passed = getResults(expect, output, "Checking for expected output", true);
+ assertTrue(passed);
+ }
+ }
+
|Groupwork| Programming Challenge : Class Pet
--------------------------------------------------
@@ -246,7 +275,7 @@ Here is the Student class again, but this time with a toString() method. Note th
:width: 150
:align: left
:alt: Animal Clinic
-
+
You've been hired to create a software system for the Awesome Animal Clinic! They would like to keep track of their animal patients. Here are some attributes of the pets that they would like to track:
- Name
@@ -255,67 +284,192 @@ You've been hired to create a software system for the Awesome Animal Clinic! The
- Type (dog, cat, lizard, etc.)
- Breed
-1. Create a class that keeps track of the attributes above for pet records at the animal clinic. Decide what instance variables are needed and their data types. Make sure you use int, double, and String data types. Make the instance variables private.
+1. Create a class that keeps track of the attributes above for pet records at
+ the animal clinic. Decide what instance variables are needed and their data
+ types. Make sure you use ``int``, ``double``, and ``String`` data types. Make
+ the instance variables ``private``.
-2. Create 2 constructors, one with no parameters and one with many parameters to initialize all the instance variables.
+2. Create a constructor with many parameters to initialize all the instance
+ variables.
-3. Create Accessor (get) methods for each of the instance variables.
+3. Create getters for each of the instance variables.
-4. Create a toString() method that returns all the information in a pet record.
+4. Create a ``toString`` method that returns all the information in a ``Pet``.
-5. In the main method below, create 3 pet objects and call their constructors, accessor methods, and toString methods to test all of your methods.
+5. In the ``main`` method below, create 2 ``Pet`` objects with different values
+ and call the constructor, accessor methods, and ``toString`` methods to test
+ all your code.
6. Make sure you use good commenting!
.. activecode:: challenge-5-4-Pet-Class
:language: java
+ :autograde: unittest
+
+ Create a Pet class that keeps track of the name, age, weight, type of animal,
+ and breed for records at an animal clinic.
- Create a Pet class that keeps track of the name, age, weight, type of animal, and breed for records at an animal clinic.
~~~~
/**
- Pet class (complete comments)
- @author
- @since
-
- */
- class Pet
+ * Pet class (complete comments)
+ *
+ * @author
+ * @since
+ */
+ class Pet
{
- // keep track of the name, age, weight, type of animal, and breed of the pet
-
-
- // Write 2 constructors, accessor (get) methods, and a toString method. Use good commenting.
-
- // Don't forget to complete the main method in the TesterClass below!
+ // keep track of the name, age, weight, type of animal, and breed of the pet
+
+ // Write a constructor, accessor (get) methods, and a toString method. Use good
+ // commenting.
+
+ // Don't forget to complete the main method in the TesterClass below!
}
-
- public class TesterClass
+
+ public class TesterClass
{
- // main method for testing
- public static void main(String[] args)
- {
- // Create 3 Pet objects and test all your methods
-
- }
- }
-
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // Create 2 Pet objects and test all your methods
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("TesterClass");
+ }
+
+ @Test
+ public void testConstructors()
+ {
+ changeClass("Pet");
+ int count = 0;
+
+ for (int i = 0; i < 6; i++)
+ {
+ if (checkConstructor(i).equals("pass")) count++;
+ }
+
+ boolean passed = count >= 1;
+
+ getResults("2+", "" + count, "Checking for constructor", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrivateVariables()
+ {
+ changeClass("Pet");
+ String expect = "5 Private";
+ String output = testPrivateInstanceVariables();
+
+ boolean passed = getResults(expect, output, "Checking Private Instance Variables");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ String target = "public * get*()";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 5;
+
+ getResults("5", "" + num, "Checking accessor (get) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "public String toString()";
+ boolean passed = checkCodeContains("toString() method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test4()
+ {
+ String code = getCode();
+ String target = "Pet * = new Pet(";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 2;
+
+ getResults("2", "" + num, "Checking main method creates 2 Pet objects", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+
+ String expect = "2+ line(s) of text";
+ String actual = " line(s) of text";
+
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 2;
+
+ getResults(expect, actual, "Checking main method prints info for 2 Pet objects", passed);
+ assertTrue(passed);
+ }
+ }
Summary
-------
-- An accessor method allows other objects to obtain the value of instance variables or static variables.
-- A non-void method returns a single value. Its header includes the return type in place of the keyword void.
+- A getter allows other objects to obtain the value of instance variables or
+ static variables.
-- Accessor methods that return primitive types use "return by value" where a copy of the value is returned.
+- A non-void method returns a single value. Its header includes the return type
+ in place of the keyword void.
-- When the return expression is a reference to an object, a copy of that reference is returned, not a copy of the object.
+- A getter is a non-void method that returns the value of an instance variable.
+ Its return type matches the type of the instance variable.
-- The return keyword is used to return the flow of control to the point immediately following where the method or constructor was called.
+- Methods "return by value" where a copy of the value is returned. When the
+ value is a primitive type, the value is copied. When the value is a reference
+ to an object, the reference is copied, not the object.
-- The toString method is an overridden method that is included in classes to provide a description of a specific object. It generally includes what values are stored in the instance data of the object.
+- The ``return`` keyword is used to return the flow of control to the point
+ immediately following where the method or constructor was called.
-- If System.out.print or System.out.println is passed an object, that object’s toString method is called, and the returned string is printed.
+- The ``toString`` method is an overridden method that is included in classes to
+ provide a description of a specific object. It generally includes what values
+ are stored in the instance data of the object.
+
+- If ``System.out.print`` or ``System.out.println`` is passed an object, that
+ object’s ``toString`` method is called, and the returned ``String`` is
+ printed.
+
+- An object’s ``toString`` method is also used to get the ``String``
+ representation used when concatenating the object to a ``String`` with the
+ ``+`` operator.
AP Practice
@@ -336,7 +490,7 @@ AP Practice
:feedback_e: The numOfPeople variable is correctly returned.
Consider the following Party class. The getNumOfPeople method is intended to allow methods in other classes to access a Party object’s numOfPeople instance variable value; however, it does not work as intended. Which of the following best explains why the getNumOfPeople method does NOT work as intended?
-
+
.. code-block:: java
public class Party
@@ -364,6 +518,7 @@ AP Practice
public class Student
{
private int id;
+
public getId()
{
return id;
@@ -372,25 +527,23 @@ AP Practice
}
The accessor method getId is intended to return the id of a Student object. Which of the following best explains why the class does not compile?
-
+
- The id instance variable should be public.
-
+
- Instance variables should be private.
-
+
- The getId method should be declared as private.
-
+
- Accessor methods should be public methods.
-
+
- The getId method requires a parameter.
-
+
- Accessor methods usually do not require parameters.
- The return type of the getId method needs to be defined as void.
-
+
- void is not the correct return type.
-
- - The return type of the getId method needs to be defined as int.
-
- + Correct! Accessor methods have a return type of the instance variable they are returning.
-
+ - The return type of the getId method needs to be defined as int.
+
+ + Correct! Accessor methods have a return type of the instance variable they are returning.
diff --git a/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst
index cf007c13c..ee528177a 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-5-mutator-methods.rst
@@ -1,249 +1,445 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-5-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
-Mutator Methods
-=================
-
-Corresponding to each get method, programmers also provide a public **set method** to change the value of a private instance variable in a class. These are called **mutator methods** (or settters or set or modifier methods). They are **void methods** meaning that they do not return a value, but they do take a **parameter**, the new value for the instance variable. Here are some examples of how to write a set method for an instance variable:
+|Time45|
+
+Mutators / Setters
+==================
+
+As we saw in the last section, since we typically make instance variables
+``private``, we have to define getters if we want to allow code outside the
+class to access the value of particular instance variables.
+
+By the same token, if we want to allow code outside the class to `change` the
+value of an instance variable we have to provide what is formally called a
+**mutator method** but which everyone actually calls a **setter**. A setter is a
+void method with a name that starts with ``set`` and that takes a single
+argument of the same type as the instance variable to be set. The effect of a
+setter, as you would probably expect, is to assign the provided value to the
+instance variable.
+
+Just as you shouldn't reflexively write a getter for every instance variable,
+you should think even harder about whether you want to write a setter. Not all
+instance variables are meant to be manipulated directly by code outside the
+class.
+
+For example, consider the ``Turtle`` class. It provides getters ``getXPos`` and
+``getYPos`` but it does not provide corresponding setters. There are, however,
+methods that change a ``Turtle``\ ’s position like ``forward`` and ``moveTo``.
+But they do more than just changing the values of instance variables; they also
+take care of drawing lines on the screen if the pen is down. By not providing
+setters for those instance variables, the authors of the ``Turtle`` class can
+assume the a ``Turtle``\ ’s position won’t change other than by going through
+one of the approved movement methods. In general, you shouldn’t write a setter
+until you find a real reason to do so.
+
+How to write a setter
+---------------------
+
+Here are some examples of how to write a setter for an instance variable:
.. code-block:: java
-
- class ExampleTemplate {
-
- //Instance variable declaration
+
+ class ExampleTemplate
+ {
+ // Instance variable declaration
private typeOfVar varName;
- // Mutator (setter) method template
+ // Setter method template
public void setVarName(typeOfVar newValue)
{
- varName = newValue;
+ varName = newValue;
}
}
-
-Here's an example of the Student class with a mutator method called setName():
+
+Here's an example of the ``Student`` class with a setter for the ``name`` variable:
.. code-block:: java
- class Student {
-
- //Instance variable name
- private String name;
-
- /** setName sets name to newName
- * @param newName */
- public void setName(String newName)
- {
- name = newName;
- }
-
- public static void main(String[] args)
- {
- // To call a set method, use objectName.setVar(newValue)
- Student s = new Student();
- s.setName("Ayanna");
- }
- }
-
-Notice the difference between set (mutator) and get (accessor) methods in the following figure. Getters return an instance variable's value and have the same return type as this variable and no parameters. Setters have a void return type and take a new value as a parameter to change the value of the instance variable.
+ class Student
+ {
+ // Instance variable name
+ private String name;
+
+ /**
+ * setName sets name to newName
+ *
+ * @param newName
+ */
+ public void setName(String newName)
+ {
+ name = newName;
+ }
+
+ public static void main(String[] args)
+ {
+ // To call a set method, use objectName.setVar(newValue)
+ Student s = new Student();
+ s.setName("Ayanna");
+ }
+ }
+
+Notice the difference between setters and getters in the following figure.
+Getters return an instance variable's value and have the same return type as
+this variable and no parameters. Setters have a void return type and take a new
+value as a parameter to change the value of the instance variable.
.. figure:: Figures/get-set-comparison.png
:width: 600px
:align: center
:figclass: align-center
- Figure 1: Comparison of set and get methods
-
-
+ Figure 1: Comparison of setters and getters
+
+
|CodingEx| **Coding Exercise**
-Try the Student class below which this time has set methods added. You will need to fix one error. The main method is in a separate Tester class and does not have access to the private instance variables in the other Student class. Change the main method so that it uses a public mutator method (set method) to access the value instead.
+Try the ``Student`` class below which has had some setters added. Notice that
+there is no ``setId`` method even though there is a ``getId``. This is
+presumably because in the system this class is part of, while it makes sense for
+a student to change their name or email, their id should never change.
+
+You will need to fix one error. The ``main`` method is in a separate class
+``TesterClass`` and does not have access to the ``private`` instance variables
+in the ```Student`` class. Change the ``main`` method so that it uses a
+``public`` setter to change the value instead.
.. activecode:: StudentObjExample2
- :language: java
+ :language: java
+ :autograde: unittest
+
+ Fix the main method to include a call to the appropriate set method.
+ ~~~~
+ public class TesterClass
+ {
+ // main method for testing
+ public static void main(String[] args)
+ {
+ Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
+ System.out.println(s1);
+ s1.setName("Skyler 2");
+ // Main doesn't have access to email, use set method!
+ s1.email = "skyler2@gmail.com";
+ System.out.println(s1);
+ }
+ }
- Fix the main method to include a call to the appropriate set method.
- ~~~~
- public class TesterClass
- {
- // main method for testing
- public static void main(String[] args)
- {
- Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
- System.out.println(s1);
- s1.setName("Skyler 2");
- // Main doesn't have access to email, use set method!
- s1.email = "skyler2@gmail.com";
- System.out.println(s1);
- }
+ class Student
+ {
+ private String name;
+ private String email;
+ private int id;
+
+ public Student(String initName, String initEmail, int initId)
+ {
+ name = initName;
+ email = initEmail;
+ id = initId;
+ }
+
+ // Setters
+
+ public void setName(String newName)
+ {
+ name = newName;
+ }
+
+ public void setEmail(String newEmail)
+ {
+ email = newEmail;
+ }
+
+ // Getters
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public String getEmail()
+ {
+ return email;
+ }
+
+ public int getId()
+ {
+ return id;
+ }
+
+ public String toString()
+ {
+ return id + ": " + name + ", " + email;
+ }
}
-
- class Student
- {
- private String name;
- private String email;
- private int id;
-
- public Student(String initName, String initEmail, int initId)
- {
- name = initName;
- email = initEmail;
- id = initId;
- }
- // mutator methods - setters
- public void setName(String newName)
- {
- name = newName;
- }
- public void setEmail(String newEmail)
- {
- email = newEmail;
- }
- public void setId(int newId)
- {
- id = newId;
- }
- // accessor methods - getters
- public String getName()
- {
- return name;
- }
- public String getEmail()
- {
- return email;
- }
- public int getId()
- {
- return id;
- }
- public String toString() {
- return id + ": " + name + ", " + email;
- }
- }
-
-|Exercise| **Check your understanding**
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ // activeCode StudentObjExample2
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("TesterClass");
+ }
+
+ @Test
+ public void test1()
+ {
+ String target = "s1.setEmail(\"skyler2@gmail.com\");";
+ boolean passed = checkCodeContains("call to setEmail()", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+ String expect = "123456: Skyler, skyler@sky.com\n123456: Skyler 2, skyler2@gmail.com";
+
+ boolean passed = getResults(expect, output, "Checking main()", true);
+ assertTrue(passed);
+ }
+ }
+|Exercise| **Check your understanding**
.. mchoice:: setSignature
:practice: T
Consider the class Party which keeps track of the number of people at the party.
-
+
.. code-block:: java
public class Party
{
- //number of people at the party
- private int numOfPeople;
+ // number of people at the party
+ private int numOfPeople;
/* Missing header of set method */
{
numOfPeople = people;
}
}
-
+
Which of the following method signatures could replace the missing header for the set method in the code above so that the method will work as intended?
- public int getNum(int people)
-
+
- The set method should not have a return value and is usually named set, not get.
-
+
- public int setNum()
-
+
- The set method should not have a return value and needs a parameter.
-
+
- public int setNum(int people)
-
+
- The set method should not have a return value.
-
+
- public void setNum(int people)
-
+
+ Yes, the set method should take a parameter called people and have a void return value. The name of the set method is usually set followed by the full instance variable name, but it does not have to be an exact match.
-
+
- public int setNumOfPeople(int p)
-
+
- The parameter of this set method should be called people in order to match the code in the method body.
-
+
.. dragndrop:: AccessorMutator
:feedback: Review the vocabulary.
:match_1: gets and returns the value of an instance variable|||accessor method
:match_2: sets the instance variable to a value in its parameter|||mutator method
- :match_3: initializes the instance variables to values|||constructor
+ :match_3: initializes the instance variables to values|||constructor
:match_4: accessible from outside the class|||public
:match_5: accessible only inside the class|||private
-
+
Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct.
-Mutator methods do not have to have a name with "set" in it, although most do. They can be any methods that change the value of an instance variable or a static variable in the class, as can be seen in the AP Practice questions below.
-
+Mutator methods do not have to have a name with "set" in it, although most do. They can be any methods that change the value of an instance variable or a static variable in the class, as can be seen in the AP Practice questions below.
+
|Groupwork| Programming Challenge : Class Pet Setters
-----------------------------------------------------
+.. |last lesson| raw:: html
+
+ last lesson
+
.. image:: Figures/animalclinic.png
:width: 150
:align: left
:alt: Animal Clinic
-
-1. Copy your Awesome Animal Clinic Pet class from the last lesson into this Active Code window.
+
+1. Copy your Awesome Animal Clinic Pet class from the |last lesson| into this Active Code window.
2. Add set methods for each of the 5 instance variables. Make sure you use good commenting!
3. Test each of the set methods in the main method.
.. activecode:: challenge-5-5-Pet-Class
:language: java
-
- Create a Pet class that keeps track of the name, age, weight, type of animal, and breed for records at an animal clinic with 2 constructors, accessor (get) methods, a toString method, and mutator (set) methods for each instance variable.
+ :autograde: unittest
+
+ Create a ``Pet`` class that keeps track of the name, age, weight, type of
+ animal, and breed for records at an animal clinic with a constructor, a
+ ``toString`` method, and getters and setters for each instance variable.
+
~~~~
/**
- Pet class (complete comments)
- @author
- @since
-
- */
- class Pet
+ * Pet class (complete comments)
+ *
+ * @author
+ * @since
+ */
+ class Pet
{
- // complete class definition with set methods
-
+ // complete class definition with set methods
+
}
-
- public class TesterClass
+
+ public class TesterClass
{
- // main method for testing
- public static void main(String[] args)
- {
- // Create Pet objects and test all your set methods
-
- }
- }
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // Create 2 Pet objects and test all your set methods
+
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ // activecode challenge-5-5-Pet-Class
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("TesterClass");
+ }
+
+ @Test
+ public void testConstructors()
+ {
+ changeClass("Pet");
+ int count = 0;
+
+ for (int i = 0; i < 6; i++)
+ {
+ if (checkConstructor(i).equals("pass")) count++;
+ }
+
+ boolean passed = count >= 1;
+
+ getResults("2+", "" + count, "Checking for constructor", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrivateVariables()
+ {
+ changeClass("Pet");
+ String expect = "5 Private";
+ String output = testPrivateInstanceVariables();
+
+ boolean passed = getResults(expect, output, "Checking Private Instance Variables");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ String target = "public * get*()";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 5;
+
+ getResults("5", "" + num, "Checking accessor (get) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "public void set*(*)";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 5;
+
+ getResults("5", "" + num, "Checking mutator (set) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "public String toString()";
+ boolean passed = checkCodeContains("toString() method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test4()
+ {
+ String code = getCode();
+ String target = "Pet * = new Pet(";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 2;
+
+ getResults("2", "" + num, "Checking main method creates 2 Pet objects", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+
+ String expect = "3+ line(s) of text";
+ String actual = " line(s) of text";
+
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 3;
+
+ getResults(expect, actual, "Checking main method prints info for 3 Pet objects", passed);
+ assertTrue(passed);
+ }
+ }
Summary
--------
-- A void method does not return a value. Its header contains the keyword void before the method name.
+- A void method does not return a value. Its header contains the keyword
+ ``void`` before the method name.
-- A **mutator method** is often a void method that changes the values of instance variables or static variables.
+- A **mutator method** or **setter** is a void method that changes the values of an instance or static
+ variable.
AP Practice
------------
@@ -252,9 +448,9 @@ AP Practice
:practice: T
Consider the following class definition.
-
+
.. code-block:: java
-
+
public class Liquid
{
private int currentTemp;
@@ -271,25 +467,25 @@ AP Practice
}
Which of the following best identifies the reason the class does not compile?
-
+
- The constructor header does not have a return type.
-
+
- The constructor should not have a return type.
-
+
- The resetTemp method is missing a return type.
-
+
- Mutator methods usually have a void return type.
-
+
- The constructor should not have a parameter.
-
+
- Constructors can have parameters.
-
+
- The resetTemp method should have a parameter.
-
+
+ Correct! The resetTemp method should have a parameter for the newTemp value to set the currentTemp.
-
+
- The instance variable currentTemp should be public instead of private.
-
+
- Instance variables should be private variables.
@@ -307,8 +503,8 @@ AP Practice
:feedback_d: Mutator methods should have a void return type.
:feedback_e: Mutator methods should have a void return type.
- In the Party class below, the addPeople method is intended to increase the value of the instance variable numOfPeople by the value of the parameter additionalPeople. The method does not work as intended.
-
+ In the ``Party`` class below, the ``addPeople`` method is intended to increase the value of the instance variable ``numOfPeople`` by the value of the parameter ``additionalPeople``. The method does not work as intended.
+
.. code-block:: java
public class Party
@@ -321,9 +517,9 @@ AP Practice
}
public int addPeople(int additionalPeople) // Line 10
- {
+ {
numOfPeople += additionalPeople; // Line 12
}
}
- Which of the following changes should be made so that the class definition compiles without error and the method addPeople works as intended?
\ No newline at end of file
+ Which of the following changes should be made so that the class definition compiles without error and the method ``addPeople`` works as intended?
diff --git a/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst
index 3c5d884a8..4ada05de5 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-6-writing-methods.rst
@@ -1,34 +1,21 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-6-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-.. index::
- single: method
+.. index::
+ single: method
single: return
single: parameter
single: argument
single: abstraction
pair: method; parameter
pair: method; argument
- pair: method; return
-
+ pair: method; return
+
+|Time90|
+
Writing Methods
=================
@@ -38,7 +25,7 @@ Up until this unit, you wrote all your code in the main method, but now we are u
- Reusing Code: avoid repetition of code. Reuse code by putting it in a method and calling it whenever needed.
- Maintainability and Debugging: smaller methods are easier to debug and understand than searching through a large main method.
-Let's look at an example with lots of repetition of code and create methods to reduce the repetition of code.
+Let's look at an example with lots of repetition of code and create methods to reduce the repetition of code. You can sing along here https://www.youtube.com/watch?v=Di23O5cN4ZU&ab_channel=Rock%27NLearn .
@@ -47,7 +34,7 @@ Let's look at an example with lots of repetition of code and create methods to r
.. clickablearea:: repeatedcode
:question: Click on all the lines that are completely identical and repeated.
:iscode:
- :feedback: Look for lines that are completely identical.
+ :feedback: Look for lines that are completely identical.
:click-incorrect:public static void main(String args[]) {:endclick:
:click-incorrect:System.out.println("This old man, he played one.");:endclick:
@@ -59,8 +46,8 @@ Let's look at an example with lots of repetition of code and create methods to r
:click-correct:System.out.println("With a knick knack paddy whack, give a dog a bone.");:endclick:
:click-correct:System.out.println("This old man came rolling home.");:endclick:
:click-incorrect:}:endclick:
-
-Did you find some repeated lines of the This Old Man song? You may have noticed that the chorus is repeated "With a knick knack paddy whack, give a dog a bone. This old man came rolling home." When you see repeated code, that is a signal for you to make a new method!
+
+Did you find some repeated lines of the `This Old Man song
- The ants go marching one by one, hurrah, hurrah
- The ants go marching one by one, hurrah, hurrah
- The ants go marching one by one
- The little one stops to suck his thumb
- And they all go marching down to the ground
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:one by one:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:suck a thumb:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
- The ants go marching two by two, hurrah, hurrah
- The ants go marching two by two, hurrah, hurrah
- The ants go marching two by two
- The little one stops to tie his shoe
- And they all go marching down to the ground
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:two by two:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:tie a shoe:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
- The ants go marching three by three, hurrah, hurrah
- The ants go marching three by three, hurrah, hurrah
- The ants go marching three by three
- The little one stops to climb a tree
- And they all go marching down to the ground
-
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick::click-incorrect:, hurrah, hurrah:endclick:
+ :click-incorrect:The ants go marching :endclick::click-correct:three by three:endclick:
+ :click-incorrect:The little one stops to :endclick::click-correct:climb a tree:endclick:
+ :click-incorrect:And they all go marching down to the ground:endclick:
+ :click-incorrect:To get out of the rain, BOOM! BOOM! BOOM! BOOM!:endclick:
-1. Print out the |The Ants Go Marching| song and circle the repeated parts of the song.
-2. In the active code window below, create a method or methods that takes parameters to print out a verse. The method(s) should be abstract enough to work for all 3 verses. Use good commenting for your methods that describe the @param. For the autograder, make sure you create a method called verse that takes 2 parameters.
+1. In the active code window below, create a method or methods that takes parameters to print out a verse. The method(s) should be abstract enough to work for all 3 verses. Use good commenting for your methods that describe the @param. For the autograder, make sure you create a method called verse that takes 2 parameters.
-3. In the main method, create an object of the class and call the method(s) you created in the last step to print out 3 verses of the song. Can you add more verses?
+2. In the main method, create an object of the class and call the method(s) you created in the last step to print out 3 verses of the song. Can you add more verses?
.. activecode:: challenge-5-6-song
:language: java
- :autograde: unittest
+ :autograde: unittest
- Create method(s) with parameters to print out verses of the song The Ants Go Marching. https://www.lyrics.com/lyric/5526512/The+Ants+Go+Marching
+ Create method(s) with parameters to print out verses of the song The Ants Go Marching. https://youtu.be/QPwEZ8Vv2YQ/The+Ants+Go+Marching
~~~~
- public class Song
- {
- // Create at least 1 method called verse that takes 2 parameters
- // that can be used to print out the verses of the song The Ants Go Marching
-
-
- public static void main(String args[])
- {
- // Create a Song object and call its method(s) to print out
- // the verses of The Ants Go Marching
- // There should be atleast 1 method called verse that takes 2 arguments.
-
-
- }
+ public class Song
+ {
+ // Create at least 1 method called verse that takes 2 parameters
+ // that can be used to print out the verses of the song The Ants Go Marching
+
+ public static void main(String args[])
+ {
+ // Create a Song object and call its method(s) to print out
+ // the verses of The Ants Go Marching
+ // There should be atleast 1 method called verse that takes 2 arguments.
+
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ /* Do NOT change Main or CodeTestHelper.java.
+ Put the active code exercise in a file like ForLoop.java.
+ Put your Junit test in the file RunestoneTests.java.
+ Run. Test by changing ForLoop.java (student code).
+ */
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
- public void checkCodeContains1(){
- //check verse 1
- boolean passed = checkCodeContains("verse method call with 2 arguments for verse 1", "verse(\"one\", \"suck his thumb\"");
- assertTrue(passed);
+ public void checkCodeContains1()
+ {
+ // check verse 1
+ boolean passed =
+ checkCodeContains(
+ "verse(...) method header with two String parameters",
+ "public void verse(String *, String *)");
+
+ assertTrue(passed);
}
@Test
- public void checkCodeContains2(){
- //check verse 2
- boolean passed = checkCodeContains("verse method call with 2 arguments for verse 2", "verse(\"two\", \"tie his shoe\"");
- assertTrue(passed);
+ public void checkCodeContains2()
+ {
+ boolean passed = checkCodeContains("a new Song object", "= new Song()");
+
+ assertTrue(passed);
}
@Test
- public void checkCodeContains3(){
- //check verse 3
- boolean passed = checkCodeContains("verse method call with 2 arguments for verse 3", "verse(\"three\", \"climb a tree\"");
- assertTrue(passed);
+ public void checkCodeContains3()
+ {
+ // check static
+ String code = getCode();
+ int actual = countOccurences(code, ".verse(");
+ String expected = "3";
+
+ boolean passed = actual >= 3;
+ getResults(
+ expected,
+ "" + actual,
+ "Checking that code contains three calls to verse(...) method using"
+ + " object.method(...) syntax",
+ passed);
+ assertTrue(passed);
}
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "The ants go marching three by three\nThe little one stops to climb a tree";
- boolean passed = output.contains(expect);
- getResults(expect, output, "Expected output from main contains 3 verses");
- assertTrue(passed);
- }
- }
+ @Test
+ public void testVerses() throws IOException
+ {
+ String output = getMethodOutput("main").replaceAll(" his ", " a ").replaceAll("\n\n", "\n");
+ String[] actualArray = output.split("\n");
+
+ boolean passed = true;
+ String error = "";
+ String expect = "No errors";
+ String actual = "No errors";
+
+ int j = 0;
+
+ for (int i = 0; i < actualArray.length; i++)
+ {
+ while (j < expectedArray.length && expectedArray[j].length() < 2) j++;
+ while (i < expectedArray.length && actualArray[i].length() < 2) i++;
+
+ if (j < expectedArray.length && actualArray[i].length() > 1)
+ {
+ /*
+ * System.out.println(expectedArray[j]);
+ * System.out.println(actualArray[i]);
+ * System.out.println();
+ */
+ if (actualArray[i].matches("[\\s\\S]*[0-9]+[\\s\\S]*"))
+ {
+ continue;
+ }
+
+ String compAct = removeSpaces(actualArray[i].toLowerCase());
+ String compExp = removeSpaces(expectedArray[j].toLowerCase());
+
+ if (!compAct.equals(compExp))
+ {
+ expect = expectedArray[j].trim();
+ actual = actualArray[i].trim() + "\n(Error on line " + (i + 1) + " of output)";
+ passed = false;
+ error =
+ "\n"
+ + "There may be more than one error! Did you forget a line?\n"
+ + "(check spelling, new lines, and punctuation carefully)";
+ break;
+ }
+ }
+
+ j++;
+ }
+
+ getResults(expect, actual, "Checking output from main" + error, passed);
+ assertTrue(passed);
+ }
+
+ private static String expectedOutput =
+ "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one\n"
+ + "The little one stops to suck a thumb\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two\n"
+ + "The little one stops to tie a shoe\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three\n"
+ + "The little one stops to climb a tree\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!";
+ private static String[] expectedArray = expectedOutput.replaceAll("\n\n", "\n").split("\n");
+ }
+
+|Groupwork| Design a Class for your Community
+----------------------------------------------------------
+
+.. |lesson 5.2| raw:: html
+
+ lesson 5.2
+
+In lessons 5.1 and 5.2, you came up with a class of your own choice relevant to your community.
+
+1. Copy your class with its 3 instance variables, constructor, and its print() and main methods from |lesson 5.2| into the active code exercise below.
+
+2. Create accessor (get) methods and mutator (set) methods for each of the instance variables.
+
+3. Create a ``toString`` method that returns all the information in the instance variables.
+
+4. Write an additional method for your class that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, e.g. ``print(format)`` could print the data according to an argument that is "plain" or "table" where the data is printed in a table drawn with dashes and lines (``|``). Or come up with another creative method for your class.
+
+5. Use these methods in the main method to test them. Make sure you use good commenting.
+
+.. activecode:: community-challenge-5-6
+ :language: java
+ :autograde: unittest
+
+ Copy your class from |lesson 5.2|. Add get, set, toString, and a method that takes a parameter. For example, there could be a print method with arguments that indicate how you want to print out the information, print(format) where format is "plain" or "table".
+ ~~~~
+ public class // Add your class name here!
+ {
+ // 1. Copy your class instance variables, constructor, and print() from 5.2.
+
+ // 2. Create accessor (get) and mutator (set) methods for each of the instance variables.
+
+ // 3. Create a toString() method that returns all the information in the instance variables.
+ // 4. Add a method for your class that takes a parameter.
+ // For example, there could be a print method with arguments that indicate
+ // how you want to print out the information, print(format) where format is "plain" or "table".
+
+ // 5. Test all the methods in the main method.
+ public static void main(String[] args)
+ {
+ // Construct an object of your class
+
+
+ // call the object's methods
+
+ }
+ }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testPrivateVariables()
+ {
+ String expect = "3 Private";
+ String output = testPrivateInstanceVariables();
+ boolean passed = false;
+ if (Integer.parseInt(expect.substring(0, 1)) <= Integer.parseInt(output.substring(0, 1)))
+ passed = true;
+ passed = getResults(expect, output, "Checking private instance variable(s)", passed);
+ assertTrue(passed);
+ }
+
+ /* @Test
+ public void testDefaultConstructor()
+ {
+ String output = checkDefaultConstructor();
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking default constructor");
+ assertTrue(passed);
+ } */
+
+ @Test
+ public void testConstructor3()
+ {
+ String output = checkConstructor(3);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking constructor with 3 parameters");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrint()
+ {
+ String output = getMethodOutput("print");
+ String expect = "More than 15 characters";
+ String actual = " than 15 characters";
+
+ if (output.length() < 15)
+ {
+ actual = "Less" + actual;
+ }
+ else
+ {
+ actual = "More" + actual;
+ }
+ boolean passed = getResults(expect, actual, "Checking print method");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main"); // .split("\n");
+ String expect = "3+ line(s) of text";
+ String actual = " line(s) of text";
+ int len = output.split("\n").length;
+
+ if (output.length() > 0)
+ {
+ actual = len + actual;
+ }
+ else
+ {
+ actual = output.length() + actual;
+ }
+ boolean passed = len >= 3;
+
+ getResults(expect, actual, "Checking output", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ String code = getCode();
+ String target = "public * get*()";
-
+ int num = countOccurencesRegex(code, target);
+ boolean passed = num >= 3;
+
+ getResults("3", "" + num, "Checking accessor (get) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String code = getCode();
+ String target = "public void set*(*)";
+
+ int num = countOccurencesRegex(code, target);
+
+ boolean passed = num >= 3;
+
+ getResults("3", "" + num, "Checking mutator (set) methods for each variable", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "public String toString()";
+ boolean passed = checkCodeContains("toString() method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testPrintFormat()
+ {
+ String target = "public void print(String";
+ boolean passed = checkCodeContains("print method with String argument", target);
+ assertTrue(passed);
+ }
+ }
Summary
-------
-- **Procedural Abstraction** (creating methods) reduces the complexity and repetition of code. We can name a block of code as a method and call it whenever we need it, abstracting away the details of how it works.
+- **Procedural Abstraction** (creating methods) reduces the complexity and repetition of code. We can name a block of code as a method and call it whenever we need it, abstracting away the details of how it works.
- A programmer breaks down a large problem into smaller subproblems by creating methods to solve each individual subproblem.
- To write methods, write a **method definition** with a **method signature** like "public void chorus()" and a **method body** in {} and method calls using an object.the method name and arguments whenever you need it to do its job.
-- To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();**
+- To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example **object.method();**
- When you call a method, you can give or pass in **arguments** or **actual parameters** to it inside the parentheses **object.method(arguments)**. The arguments are saved in local **formal parameter** variables that are declared in the method header, for example: public void method(type param1, type param2) { ... }.
@@ -522,7 +834,7 @@ AP Practice
:practice: T
Consider the following class, which uses the instance variable dollars to represent the money in a wallet in dollars.
-
+
.. code-block:: java
public class Wallet
@@ -536,49 +848,49 @@ AP Practice
}
The putMoneyInWallet method is intended to increase the dollars in the wallet by the parameter amount and then return the updated dollars in the wallet. Which of the following code segments should replace *missing code* so that the putMoneyInWallet method will work as intended?
-
+
- .. code-block:: java
amount += dollars;
return dollars;
- dollars should be incremented by amount.
-
+
- .. code-block:: java
dollars = amount;
return amount;
-
+
- dollars should be incremented by amount.
-
+
- .. code-block:: java
dollars += amount;
return dollars;
-
+
+ Correct.
- .. code-block:: java
dollars = dollars + amount;
return amount;
-
+
- amount is returned instead of dollars.
-
+
- .. code-block:: java
amount = dollars + amount;
return dollars;
-
+
- dollars should be incremented by amount.
-
+
.. mchoice:: AP5-6-2
:practice: T
Consider the Liquid class below.
-
+
.. code-block:: java
public class Liquid
@@ -598,8 +910,8 @@ AP Practice
}
}
- The isBoiling method is intended to return true if increasing the currentTemp by the parameter amount is greater than or equal to the boilingPoint, or otherwise return false. Which of the following code segments can replace *missing code* to ensure that the isBoiling method works as intended?
-
+ The isBoiling method is intended to return true if increasing the currentTemp by the parameter amount is greater than or equal to the boilingPoint, or otherwise return false. Which of the following code segments can replace *missing code* to ensure that the isBoiling method works as intended?
+
.. code-block:: java
I. if (currentTemp + amount < boilingPoint)
@@ -628,22 +940,21 @@ AP Practice
}
- I only
-
+
- I would work but it is not the only code that would work.
- II only
-
+
- II does not check against the boilingPoint and does not return only boolean values.
-
+
- III only
-
+
- III would work but it is not the only code that would work.
- I and III only.
-
- + Correct!
-
+
+ + Correct!
+
- I, II, III
-
- - II does not check against the boilingPoint and does not return only boolean values.
+ - II does not check against the boilingPoint and does not return only boolean values.
diff --git a/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst b/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst
index 2b6fef4ee..96519e991 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-7-static-vars-methods.rst
@@ -1,47 +1,35 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-7-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
+|Time45|
+
Static Variables and Methods
============================
In Unit 2, we explored the Math class and its many static methods like Math.random(), and we've always used a main method which is static. In this lesson, you will learn to write your own static variables and methods.
-- **Static** variables and methods belong to a class and are called with the Class Name rather than using object variables, like ClassName.methodName();
+- **Static** variables and methods belong to a class and are called with the Class Name rather than using object variables, like ClassName.methodName();
-- There is only one copy of a static variable or method for the whole class. For example, the main method is static because there should only be 1 main method.
+- There is only one copy of a static variable or method for the whole class. For example, the main method is static because there should only be 1 main method.
- Static methods can be public or private.
-- The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
+- The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
.. code-block:: java
-
- class ClassName {
+
+ class ClassName
+ {
// static variable
public static type variableName;
-
+
// static method
- public static returnType methodName(parameters) {
- // implementation not shown
+ public static returnType methodName(parameters)
+ {
+ // implementation not shown
}
}
// To call a static method or variable, use the Class Name
@@ -54,7 +42,7 @@ In Unit 2, we explored the Math class and its many static methods like Math.rand
Static methods only have access to other static variables and static methods. Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.
-Since there is only 1 copy of a static variable or method, static variables are often used to count how many objects are generated. In the following class Person, there is a static variable called personCounter that is incremented each time the Person constructor is called to initialize a new Person object. The static method printCounter() prints out its value. You can also watch how it works in the |Java visualizer| by clicking the CodeLens button below.
+Since there is only 1 copy of a ``static`` variable or method, static variables are often used to count how many objects are generated. In the following class ``Person``, there is a ``static`` variable called ``personCounter`` that is incremented each time the ``Person`` constructor is called to initialize a new ``Person`` object. The static method ``printCounter`` prints out its value. You can also watch how it works in the |Java visualizer| by clicking the CodeLens button below.
.. activecode:: PersonClassStaticCounter
:language: java
@@ -62,121 +50,128 @@ Since there is only 1 copy of a static variable or method, static variables are
What will the following code print out? Try adding another Person object and see what happens. Try the CodeLens button to run the code step by step.
~~~~
- public class Person
+ public class Person
{
- // instance variables
- private String name;
- private String email;
- private String phoneNumber;
-
- // Static counter variable
- public static int personCounter = 0;
-
- // static method to print out counter
- public static void printPersonCounter() {
+ // instance variables
+ private String name;
+ private String email;
+ private String phoneNumber;
+
+ // Static counter variable
+ public static int personCounter = 0;
+
+ // static method to print out counter
+ public static void printPersonCounter()
+ {
System.out.println("Person counter: " + personCounter);
- }
-
- // constructor: construct a Person copying in the data into the instance variables
- public Person(String initName, String initEmail, String initPhone)
- {
- name = initName;
- email = initEmail;
- phoneNumber = initPhone;
- personCounter++;
- }
-
- // toString() method
- public String toString()
- {
- return name + ": " + email + " " + phoneNumber;
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // call the constructor to create a new person
- Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
- Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955");
-
- Person.printPersonCounter();
- }
+ }
+
+ // constructor: construct a Person copying in the data into the instance
+ // variables
+ public Person(String initName, String initEmail, String initPhone)
+ {
+ name = initName;
+ email = initEmail;
+ phoneNumber = initPhone;
+ personCounter++;
+ }
+
+ // toString() method
+ public String toString()
+ {
+ return name + ": " + email + " " + phoneNumber;
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // call the constructor to create a new person
+ Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
+ Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955");
+
+ Person.printPersonCounter();
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
@Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Person counter: 2";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
-
-
+ public void testMain() throws IOException
+ {
+ Person.personCounter = 0;
+ String output = getMethodOutput("main");
+ String expect = "Person counter: 2";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+ }
+
Another common use for static variables is the keep track of a minimum or maximum value or an average of the values in a collection of objects.
|Exercise| **Check Your Understanding**
.. mchoice:: staticTrace
:practice: T
-
+
Consider the class Temperature below which has a static variable. What is the output of the main method below?
-
+
.. code-block:: java
-
- public class Temperature
+
+ public class Temperature
{
- private double temperature;
- public static double maxTemp = 0;
+ private double temperature;
+ public static double maxTemp = 0;
- public Temperature(double t)
- {
+ public Temperature(double t)
+ {
temperature = t;
if (t > maxTemp)
- maxTemp = t;
- }
+ {
+ maxTemp = t;
+ }
+ }
- public static void main(String[] args)
- {
+ public static void main(String[] args)
+ {
Temperature t1 = new Temperature(75);
Temperature t2 = new Temperature(100);
Temperature t3 = new Temperature(65);
System.out.println("Max Temp: " + Temperature.maxTemp);
- }
- }
+ }
+ }
- Max Temp: 0
-
+
- maxTemp is changed in each call to the Temperature() constructor.
-
+
- There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor.
-
+
- Non-static methods and constructors can use any instance or static variables in the class.
-
+
- Max Temp: 100
-
+
+ Yes, maxTemp is initialized to 0 and then changed to 75 and then 100 by the constructor calls.
-
+
- Max Temp: 75
-
+
- maxTemp will be changed to 100 by the second constructor call since 100 > 75.
-
+
- Max Temp: 65
-
+
- maxTemp will not be changed to 65 by the third constructor call because 67 is not > 100.
-
+
.. |visualizer2| raw:: html
Java visualizer
-
+
You can see this code in action in the |visualizer2|.
|CodingEx| **Coding Exercise**
@@ -186,98 +181,277 @@ You can see this code in action in the |visualizer2|.
:autograde: unittest
:practice: T
- Fix the bugs in the following code.
+ Fix the bugs in the following code.
~~~~
- public class Temperature
+ public class Temperature
{
- private double temperature;
- public static double maxTemp = 0;
-
- public Temperature(double t)
- {
- temperature = t;
- if (t > maxTemp)
- maxTemp = t;
- }
-
- public static printMax()
- {
- System.out.println(temperature);
- }
-
- public static void main(String[] args)
- {
- Temperature t1 = new Temperature(75);
- Temperature t2 = new Temperature(100);
- Temperature.printMax();
- }
- }
+ private double temperature;
+ public static double maxTemp = 0;
+
+ public Temperature(double t)
+ {
+ temperature = t;
+ if (t > maxTemp)
+ {
+ maxTemp = t;
+ }
+ }
+
+ public static printMax()
+ {
+ System.out.println(temperature);
+ }
+
+ public static void main(String[] args)
+ {
+ Temperature t1 = new Temperature(75);
+ Temperature t2 = new Temperature(100);
+ Temperature.printMax();
+ }
+ }
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- @Test
- public void testCodeContains1()
- {
-
- boolean passed = checkCodeContains("return type of printMax()", "public static void printMax()");
- assertTrue(passed);
- }
-
- @Test
- public void testCodeContains2()
- {
-
- boolean passed = checkCodeContains("static variable maxTemp in static function", "System.out.println(maxTemp);");
- assertTrue(passed);
- }
-
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "100.0";
- boolean passed = getResults(expect, output, "Expected output from main", true);
- assertTrue(passed);
- }
- }
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testCodeContains1()
+ {
+
+ boolean passed =
+ checkCodeContains("static printMax() header", "public static void printMax()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCodeContains2()
+ {
+ String code = getCode();
+ boolean passed =
+ code.contains("System.out.println(maxTemp);")
+ || code.contains("System.out.println(Temperature.maxTemp);");
+ getResults("true", "" + passed, "printMax method returns the right value", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "100.0";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
|Groupwork| Programming Challenge : Static Song and counter
------------------------------------------------------------
.. |The Ants Go Marching| raw:: html
- The Ants Go Marching
+ The Ants Go Marching
+
+.. |last lesson| raw:: html
+
+ last lesson
-In the last lesson, we wrote a class with methods to print out the song |The Ants Go Marching|. Notice that this is a class where there are no instance variables and we don't really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With the Song, we can just make the methods static and have just 1 copy of them.
+In the |last lesson|, we wrote a class with methods to print out the song |The Ants Go Marching|. Notice that this is a class where there are no instance variables and we don't really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With the Song, we can just make the methods static and have just 1 copy of them.
-1. Copy in your class from the last lesson into this active code window. Change the method(s) that print out the verses of the Song to be static. In the main method, change how you call the static methods by using just the classname instead of creating an object.
+1. Copy in your class from the |last lesson| into this active code window. Change the method(s) that print out the verses of the Song to be static. In the main method, change how you call the static methods by using just the classname instead of creating an object.
-2. Add a static variable to the class that keeps track of the number of verses. Increment this variable each time the method to print a verse is called and print it out.
+2. Add a public static variable called **numVerses** to the class that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.
.. activecode:: challenge-5-7-static-song
:language: java
+ :autograde: unittest
+
+ public class Song
+ {
+ // Add a public static variable called numVerses
+
+ // Change the method(s) to be static
+
+ public static void main(String args[])
+ {
+ // Call the static method(s) to print out the Song
+ // Print out the static variable numVerses
- public class Song
- {
- // Add a static verse counter variable
-
-
- // Change the method(s) to be static
-
-
-
- public static void main(String args[])
- {
- // Call the static method(s) to print out the Song
-
- }
+ }
}
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ /* Do NOT change Main or CodeTestHelper.java.
+ Put the active code exercise in a file like ForLoop.java.
+ Put your Junit test in the file RunestoneTests.java.
+ Run. Test by changing ForLoop.java (student code).
+ */
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @After
+ public void tearDown()
+ {
+ super.tearDown();
+ // Song.numVerses = 0;
+
+ }
+
+ @Test
+ public void checkCodeContains1()
+ {
+ // check verse 1
+ boolean passed =
+ checkCodeContains(
+ "verse(...) method header with two String parameters",
+ "public static void verse(String *, String *)");
+
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeContains2()
+ {
+ // check static
+ String code = getCode();
+ int actual = countOccurences(code, "Song.verse(");
+ String expected = "3";
+
+ boolean passed = actual >= 3;
+ getResults(
+ expected,
+ "" + actual,
+ "Checking that code contains three calls to verse(...) method using"
+ + " ClassName.staticMethod(...) syntax",
+ passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeContains3()
+ {
+ // check static
+ String code = getCode();
+ int actual = countOccurences(code, "public static int numVerses = 0");
+ String expected = "1";
+
+ boolean passed = actual >= 1;
+ getResults(
+ expected,
+ "" + actual,
+ "Checking that code declares variable numVerses according to instructions and sets"
+ + " it to zero",
+ passed);
+
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeContains4()
+ {
+ // check static
+ String code = getCode();
+ boolean increment = code.contains("numVerses++");
+ String expected = "increments: true\n";
+ String actual = "increments: " + increment + "\n";
+
+ String anytext = "[\\s\\S]*";
+ String regex = "System.out.print[ln]*\\([\"a-zA-Z0-9 +]*numVerses[\"a-zA-Z0-9 +]*\\);";
+ boolean printed = code.matches(anytext + regex + anytext);
+ expected += "prints: true";
+ actual += "prints: " + printed;
+
+ boolean passed = increment && printed;
+ getResults(expected, actual, "Checking that code increments and prints numVerses", passed);
+
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testVerses() throws IOException
+ {
+ String output = getMethodOutput("main").replaceAll(" his ", " a ").replaceAll("\n\n", "\n");
+ String[] actualArray = output.split("\n");
+
+ boolean passed = true;
+ String error = "";
+ String expect = "No errors";
+ String actual = "No errors";
+
+ int j = 0;
+
+ for (int i = 0; i < actualArray.length; i++)
+ {
+ while (j < expectedArray.length && expectedArray[j].length() < 2) j++;
+ while (i < expectedArray.length && actualArray[i].length() < 2) i++;
+
+ if (j < expectedArray.length && actualArray[i].length() > 1)
+ {
+ /*
+ * System.out.println(expectedArray[j]);
+ * System.out.println(actualArray[i]);
+ * System.out.println();
+ */
+ if (actualArray[i].matches("[\\s\\S]*[0-9]+[\\s\\S]*"))
+ {
+ continue;
+ }
+
+ String compAct = removeSpaces(actualArray[i].toLowerCase());
+ String compExp = removeSpaces(expectedArray[j].toLowerCase());
+
+ if (!compAct.equals(compExp))
+ {
+ expect = expectedArray[j].trim();
+ actual = actualArray[i].trim() + "\n(Error on line " + (i + 1) + " of output)";
+ passed = false;
+ error =
+ "\n"
+ + "There may be more than one error! Did you forget a line?\n"
+ + "(check spelling, new lines, and punctuation carefully)";
+ break;
+ }
+ }
+
+ j++;
+ }
+
+ getResults(expect, actual, "Checking output from main" + error, passed);
+ assertTrue(passed);
+ }
+
+ private static String expectedOutput =
+ "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one, hurrah, hurrah\n"
+ + "The ants go marching one by one\n"
+ + "The little one stops to suck a thumb\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two, hurrah, hurrah\n"
+ + "The ants go marching two by two\n"
+ + "The little one stops to tie a shoe\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n"
+ + "\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three, hurrah, hurrah\n"
+ + "The ants go marching three by three\n"
+ + "The little one stops to climb a tree\n"
+ + "And they all go marching down to the ground\n"
+ + "To get out of the rain, BOOM! BOOM! BOOM! BOOM!";
+ private static String[] expectedArray = expectedOutput.replaceAll("\n\n", "\n").split("\n");
+ }
Summary
-------
diff --git a/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst b/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst
index 7053afe07..10acd4726 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-8-scope-access.rst
@@ -1,29 +1,21 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-8-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
+|Time45|
+
Scope and Access
=================
-The **scope** of a variable is defined as where a variable is accessible or can be used. The scope is determined by where you declare the variable when you write your programs. When you declare a variable, look for the closest enclosing curly brackets { } -- this is its scope.
+.. index::
+ single: scope
+ single: access
+ single: local variable
+
+
+The **scope** of a variable is defined as where a variable is accessible or can be used. The scope is determined by where you declare the variable when you write your programs. When you declare a variable, look for the closest enclosing curly braces (``{}``) -- this is its scope.
Java has 3 levels of scope that correspond to different types of variables:
@@ -33,7 +25,7 @@ Java has 3 levels of scope that correspond to different types of variables:
- **Block Level Scope** for **loop variables** and other local variables defined inside of blocks of code with { }.
-The image below shows these 3 levels of scope.
+The image below shows these 3 levels of scope.
.. figure:: Figures/scopeDiagram.png
:width: 500px
@@ -42,7 +34,7 @@ The image below shows these 3 levels of scope.
:figclass: align-center
Figure 1: Class, Method, and Block Level Scope
-
+
|Exercise| Check Your Understanding
.. clickablearea:: name_class_scope
@@ -50,36 +42,38 @@ The image below shows these 3 levels of scope.
:iscode:
:feedback: Remember that the instance variables declared at the top of the class have Class Scope.
- :click-incorrect:public class Name {:endclick:
-
+ :click-incorrect:public class Name:endclick:
+ :click-incorrect:{:endclick:
:click-correct:private String first;:endclick:
:click-correct:public String last;:endclick:
-
- :click-incorrect:public Name(String theFirst, String theLast) {:endclick:
+
+ :click-incorrect:public Name(String theFirst, String theLast):endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:String firstName = theFirst;:endclick:
:click-incorrect:first = firstName;:endclick:
:click-incorrect:last = theLast;:endclick:
- :click-incorrect:}:endclick:
- :click-incorrect:}:endclick:
-
+ :click-incorrect:}:endclick:
+ :click-incorrect:}:endclick:
+
.. clickablearea:: name_method_scope
:question: Click on all the variable declarations that are at Method Level Scope.
:iscode:
:feedback: Remember that the parameter variables and the local variables declared inside a method have Method Level Scope.
- :click-incorrect:public class Name {:endclick:
-
+ :click-incorrect:public class Name:endclick:
+ :click-incorrect:{:endclick:
:click-incorrect:private String first;:endclick:
:click-incorrect:public String last;:endclick:
-
- :click-correct:public Name(String theFirst, String theLast) {:endclick:
+
+ public Name(:click-correct:String theFirst:endclick:, :click-correct:String theLast:endclick:)
+ :click-incorrect:{:endclick:
:click-correct:String firstName = theFirst;:endclick:
:click-incorrect:first = firstName;:endclick:
:click-incorrect:last = theLast;:endclick:
- :click-incorrect:}:endclick:
- :click-incorrect:}:endclick:
+ :click-incorrect:}:endclick:
+ :click-incorrect:}:endclick:
-**Local variables** are variables that are declared inside a method, usually at the top of the method. These variables can only be used within the method and do not exist outside of the method. Parameter variables are also considered local variables that only exist for that method. It's good practice to keep any variables that are used by just one method as local variables in that method.
+**Local variables** are variables that are declared inside a method, usually at the top of the method. These variables can only be used within the method and do not exist outside of the method. Parameter variables are also considered local variables that only exist for that method. It's good practice to declare any variables that are used by just one method as local variables in that method.
Instance variables at class scope are shared by all the methods in the class and can be marked as public or private with respect to their access outside of the class. They have Class scope regardless of whether they are public or private.
@@ -92,73 +86,123 @@ Another way to look at scope is that a variable's scope is where it lives and ex
.. activecode:: PersonScope
:language: java
+ :autograde: unittest
- Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Explain to someone sitting next to you why you can't access these. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope.
+ Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Explain to someone sitting next to you why you can't access these. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope.
~~~~
- public class Person
+ public class Person
{
- private String name;
- private String email;
-
- public Person(String initName, String initEmail)
- {
- name = initName;
- email = initEmail;
- }
-
- public String toString()
- {
- for (int i=0; i < 5; i++) {
- int id = i;
- }
- // Can you access the blockScope variables i or id?
- System.out.println("i at the end of the loop is " + i);
- System.out.println("The last id is " + id);
-
- // Can toString() access parameter variables in Person()?
- return initName + ": " + initEmail;
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // call the constructor to create a new person
- Person p1 = new Person("Sana", "sana@gmail.com");
- System.out.println(p1);
- }
+ private String name;
+ private String email;
+
+ public Person(String initName, String initEmail)
+ {
+ name = initName;
+ email = initEmail;
+ }
+
+ public String toString()
+ {
+ for (int i = 0; i < 5; i++)
+ {
+ int id = i;
+ }
+ // Can you access the blockScope variables i or id?
+ System.out.println("i at the end of the loop is " + i);
+ System.out.println("The last id is " + id);
+
+ // Can toString() access parameter variables in Person()?
+ return initName + ": " + initEmail;
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // call the constructor to create a new person
+ Person p1 = new Person("Sana", "sana@gmail.com");
+ System.out.println(p1);
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testCodeContains()
+ {
+ boolean passed =
+ checkCodeContains("returning instance variables", "return name + \": \" + email;");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testCodeContains2()
+ {
+ boolean passed =
+ checkCodeContains("declaration and initialization of id to 0", "int id = 0;");
+ assertTrue(passed);
+ }
}
If there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable, as seen below. We'll see in the next lesson, that we can distinguish between the local variable and the instance variable using the keyword this to refer to this object's instance variables.
.. activecode:: PersonLocalVar
:language: java
+ :autograde: unittest
+
+ In this example, the local variable is used instead of the instance variable of the same name. What will the code print out? Try it with the CodeLens button.
+ ~~~~
+ public class Person
+ {
+ private String name;
+ private String email;
+
+ public Person(String initName, String initEmail)
+ {
+ name = initName;
+ email = initEmail;
+ }
+
+ public String toString()
+ {
+ String name = "unknown";
+ // The local variable name here will be used,
+ // not the instance variable name.
+ return name + ": " + email;
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ // call the constructor to create a new person
+ Person p1 = new Person("Sana", "sana@gmail.com");
+ System.out.println(p1);
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
- public class Person
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
{
- private String name;
- private String email;
-
- public Person(String initName, String initEmail)
- {
- name = initName;
- email = initEmail;
- }
-
- public String toString()
- {
- String name = "unknown";
- // The local variable name here will be used,
- // not the instance variable name.
- return name + ": " + email;
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- // call the constructor to create a new person
- Person p1 = new Person("Sana", "sana@gmail.com");
- System.out.println(p1);
- }
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "unknown: sana@gmail.com";
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
}
|Groupwork| Programming Challenge : Debugging
@@ -168,50 +212,139 @@ If there is a local variable with the same name as an instance variable, the var
.. activecode:: challenge-5-8-Debug
:language: java
+ :autograde: unittest
+ :practice: T
- Debug the following program that has scope violations. Then, add comments that label the variable declarations as class, method, or block scope.
+ Debug the following program that has scope violations. You may need to add methods or use methods that are in the class Fraction appropriately. Then, add comments that label the variable declarations as class, method, or block scope.
~~~~
- public class TesterClass
+ public class TesterClass
{
- public static void main(String[] args)
- {
- Fraction f1 = new Fraction();
- Fraction f2 = new Fraction(1,2);
- System.out.println(f1);
- System.out.println(f2.numerator / f2.denominator);
- }
- }
-
+ public static void main(String[] args)
+ {
+ Fraction f1 = new Fraction();
+ Fraction f2 = new Fraction(1, 2);
+ System.out.println(f1);
+ System.out.println(f2.numerator / f2.denominator);
+ }
+ }
+
/** Class Fraction */
class Fraction
{
- // instance variables
- private int numerator;
- private int denominator;
-
- // constructor: set instance variables to default values
- public Fraction()
- {
- int d = 1;
- numerator = d;
- denominator = d;
- }
-
- // constructor: set instance variables to init parameters
- public Fraction(int initNumerator, int initDenominator)
- {
- numerator = initNumerator;
- denominator = initDenominator;
- }
-
- public String toString()
- {
- // if the denominator is 1, then just return the numerator
- if (denominator == d) {
- int newNumerator = 1;
- }
- return newNumerator + "/" + denominator;
- }
+ // instance variables
+ private int numerator;
+ private int denominator;
+
+ // constructor: set instance variables to default values
+ public Fraction()
+ {
+ int d = 1;
+ numerator = d;
+ denominator = d;
+ }
+
+ // constructor: set instance variables to init parameters
+ public Fraction(int initNumerator, int initDenominator)
+ {
+ numerator = initNumerator;
+ denominator = initDenominator;
+ }
+
+ public String toString()
+ {
+ // if the denominator is 1, then just return the numerator
+ if (denominator == d)
+ {
+ int newNumerator = 1;
+ }
+ return newNumerator + "/" + denominator;
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("TesterClass");
+ }
+
+ @Test
+ public void test1()
+ {
+ String orig =
+ "public class TesterClass\n"
+ + "{\n"
+ + " public static void main(String[] args)\n"
+ + " {\n"
+ + " Fraction f1 = new Fraction();\n"
+ + " Fraction f2 = new Fraction(1,2);\n"
+ + " System.out.println(f1);\n"
+ + " System.out.println(f2.numerator / f2.denominator);\n"
+ + " }\n"
+ + " }\n\n"
+ + "/** Class Fraction */\n"
+ + "class Fraction\n"
+ + "{\n"
+ + " // instance variables\n"
+ + " private int numerator;\n"
+ + " private int denominator;\n\n"
+ + " // constructor: set instance variables to default values\n"
+ + " public Fraction()\n"
+ + " {\n"
+ + " int d = 1;\n"
+ + " numerator = d;\n"
+ + " denominator = d;\n"
+ + " }\n\n"
+ + " // constructor: set instance variables to init parameters\n"
+ + " public Fraction(int initNumerator, int initDenominator)\n"
+ + " {\n"
+ + " numerator = initNumerator;\n"
+ + " denominator = initDenominator;\n"
+ + " }\n\n"
+ + " public String toString()\n"
+ + " {\n"
+ + " // if the denominator is 1, then just return the numerator\n"
+ + " if (denominator == d) {\n"
+ + " int newNumerator = 1;\n"
+ + " }\n"
+ + " return newNumerator + \"/\" + denominator;\n"
+ + " }\n"
+ + "}\n";
+
+ boolean passed = codeChanged(orig);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String expect = "1\n1/2";
+ String actual = getMethodOutput("main");
+
+ boolean passed = getResults(expect, actual, "Testing main()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String code = getCodeWithoutComments();
+ int count = countOccurences(code, "private");
+ boolean passed = (count >= 2);
+ getResults(
+ "2 private vars",
+ count + " private vars",
+ "Keep the instance variables private! Use other Fraction methods.",
+ passed);
+ assertTrue(passed);
+ }
}
Summary
@@ -245,9 +378,9 @@ AP Practice
:correct: d
Consider the following class definitions. Which of the following best explains why the class will not compile?
-
+
.. code-block:: java
-
+
public class Party
{
private int boxesOfFood;
@@ -265,17 +398,17 @@ AP Practice
boxesOfFood = updatedAmountOfFood;
}
- public void eatFoodBoxes(int eatenBoxes)
+ public void eatFoodBoxes(int eatenBoxes)
{
boxesOfFood = updatedAmountOfFood - eatenBoxes;
}
}
-
+
.. mchoice:: AP5-8-2
:practice: T
Consider the following class definition.
-
+
.. code-block:: java
public class Movie
@@ -304,23 +437,23 @@ AP Practice
Which of the following reasons explains why the printPrice method is "broken" and only ever prints out a value of 16?
- The private variables currentPrice and movieRating are not properly initialized.
-
+
- The constructor will initialize them.
- The private variables currentPrice and movieRating should have been declared public.
-
+
- Instance variables should be private.
- The printPrice method should have been declared as private.
-
+
- Methods are usually public.
- currentPrice is declared as a local variable in the getCurrentPrice method and set to 16, and will be used instead of the instance variable currentPrice.
-
+
+ Correct!
- The currentPrice instance variable does not have a value.
-
+
- Accessor methods are usually public.
diff --git a/_sources/Unit5-Writing-Classes/topic-5-9-this.rst b/_sources/Unit5-Writing-Classes/topic-5-9-this.rst
index 30eca2425..efdb57e7d 100644
--- a/_sources/Unit5-Writing-Classes/topic-5-9-this.rst
+++ b/_sources/Unit5-Writing-Classes/topic-5-9-this.rst
@@ -1,109 +1,135 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 5-9-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
-
+|Time45|
+
this Keyword
=================
-The keyword **this** can be used in a class to refer to the current calling object.
+The keyword ``this`` can be used in a class to refer to the current calling object.
-.. |Java visualizer| raw:: html
+For example, in the following Class Person, when we create an object p1 and call the constructor or p1.setEmail(), the word "this" refers to p1. And when we make the same method calls with object p2, "this" refers to p2.
+Run the code below and also check it out in the Java visualizer with the Show CodeLens button which shows how this refers to different objects when the code is run.
- Java visualizer
-
-For example, in the following Class Person, when we create an object p1 and call the constructor or p1.setEmail(), the word "this" refers to p1. And when we make the same method calls with object p2, "this" refers to p2.
-Run the code below and also check it out in the |Java visualizer| which shows how this refers to different objects when the code is run.
-
.. activecode:: PersonClassThis
:language: java
+ :autograde: unittest
- Observe the use of the keyword this in the code below.
+ Observe the use of the keyword this in the code below. Click on the CodeLens button and then forward to see the memory in action.
~~~~
- public class Person
+ public class Person
{
- // instance variables
+ // instance variables
private String name;
private String email;
private String phoneNumber;
-
- // constructor
- public Person(String theName)
- {
- this.name = theName;
- }
-
- // accessor methods - getters
- public String getName() { return this.name;}
- public String getEmail() { return this.email;}
- public String getPhoneNumber() { return this.phoneNumber;}
-
- // mutator methods - setters
- public void setName(String theName) { this.name = theName;}
- public void setEmail(String theEmail) {this.email = theEmail;}
- public void setPhoneNumber(String thePhoneNumber) { this.phoneNumber = thePhoneNumber;}
- public String toString()
- {
- return this.name + " " + this.email + " " + this.phoneNumber;
- }
-
- // main method for testing
- public static void main(String[] args)
- {
- Person p1 = new Person("Sana");
- System.out.println(p1);
- Person p2 = new Person("Jean");
- p2.setEmail("jean@gmail.com");
- p2.setPhoneNumber("404 899-9955");
- System.out.println(p2);
- }
+
+ // constructor
+ public Person(String theName)
+ {
+ this.name = theName;
+ }
+
+ // accessor methods - getters
+ public String getName()
+ {
+ return this.name;
+ }
+
+ public String getEmail()
+ {
+ return this.email;
+ }
+
+ public String getPhoneNumber()
+ {
+ return this.phoneNumber;
+ }
+
+ // mutator methods - setters
+ public void setName(String theName)
+ {
+ this.name = theName;
+ }
+
+ public void setEmail(String theEmail)
+ {
+ this.email = theEmail;
+ }
+
+ public void setPhoneNumber(String thePhoneNumber)
+ {
+ this.phoneNumber = thePhoneNumber;
+ }
+
+ public String toString()
+ {
+ return this.name + " " + this.email + " " + this.phoneNumber;
+ }
+
+ // main method for testing
+ public static void main(String[] args)
+ {
+ Person p1 = new Person("Sana");
+ System.out.println(p1);
+ Person p2 = new Person("Jean");
+ p2.setEmail("jean@gmail.com");
+ p2.setPhoneNumber("404 899-9955");
+ System.out.println(p2);
+ }
}
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Person");
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Sana null null\nJean jean@gmail.com 404 899-9955";
+
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
+ }
+
.. note::
- Note that in the code above, this.name, this.email, and this.phoneNumber are equivalent to writing just name, email, and phoneNumber, but ``this.variable`` is a way to indicate that we are referring to the instance variables of this object instead of a local variable.
+ Note that in the code above, this.name, this.email, and this.phoneNumber are equivalent to writing just name, email, and phoneNumber, but ``this.variable`` is a way to indicate that we are referring to the instance variables of this object instead of a local variable.
-Static methods cannot refer to this or instance variables because they are called with the classname, not an object, so there is no this object.
+Static methods cannot refer to this or instance variables because they are called with the classname, not an object, so there is no this object.
The keyword this is sometimes used by programmers to distinguish between variables. Programmers can give the parameter variables the same names as the instance variables and this can distinguish them and avoid a naming conflict. For example, both the instance variable and the parameter variable are called name in the code below.
.. code-block:: java
-
- // instance variables
+
+ // instance variables
private String name;
-
+
// constructor
public Person(String name)
{
// Set this object's instance variable name to the parameter variable name
- this.name = name;
+ this.name = name;
}
-
-.. |Java visualizer2| raw:: html
-
- Java visualizer
-
-The **this** variable can be used anywhere you would use an object variable. You can even pass it to another method as an argument. Consider the classes below, Pay and Overtime. The Pay class declares an Overtime object and passes in **this** (the current Pay object) to its constructor which computes the overtime with respect to that Pay object. Try this code in the |Java visualizer2|. Here is an image that shows how this and myPay and p all refer to the same object in memory.
+The ``this`` variable can be used anywhere you would use an object variable. You can even pass it to another method as an argument. Consider the classes below, ``Pay`` and ``Overtime``. The ``Pay`` class declares an ``Overtime`` object and passes in ``this`` (the current ``Pay`` object) to its constructor which computes the overtime with respect to that ``Pay`` object. Try this code in the active code exercise below with the Show CodeLens button to trace through it step by step. Here is an image that shows how ``this``, ``myPay`` and ``p`` all refer to the same object in memory.
.. figure:: Figures/thisTrace.png
:width: 400px
@@ -112,52 +138,73 @@ The **this** variable can be used anywhere you would use an object variable. Yo
.. activecode:: PayClassThis
:language: java
-
- What does this code print out? Trace through the code. Notice how the this Pay object is passed to the Overtime constructor.
+ :autograde: unittest
+
+ What does this code print out? Trace through the code with the Show CodeLens button. Notice how the this Pay object is passed to the Overtime constructor.
~~~~
public class Pay
{
- private double pay;
+ private double pay;
- public Pay(double p)
- {
- pay = p;
- }
+ public Pay(double p)
+ {
+ pay = p;
+ }
- public double getPay()
- {
- return pay;
- }
+ public double getPay()
+ {
+ return pay;
+ }
- public void calculatePayWithOvertime()
- {
- // this Pay object is passed to the Overtime constructor
- Overtime ot = new Overtime(this);
- pay = ot.getOvertimePay();
- }
-
- public static void main(String[] args)
- {
- Pay myPay = new Pay(100.0);
- myPay.calculatePayWithOvertime();
- System.out.println(myPay.getPay());
- }
+ public void calculatePayWithOvertime()
+ {
+ // this Pay object is passed to the Overtime constructor
+ Overtime ot = new Overtime(this);
+ pay = ot.getOvertimePay();
+ }
+
+ public static void main(String[] args)
+ {
+ Pay myPay = new Pay(100.0);
+ myPay.calculatePayWithOvertime();
+ System.out.println(myPay.getPay());
+ }
}
class Overtime
{
- private double payWithOvertime;
+ private double payWithOvertime;
- public Overtime(Pay p)
- {
- payWithOvertime = p.getPay() * 1.5;
- }
+ public Overtime(Pay p)
+ {
+ payWithOvertime = p.getPay() * 1.5;
+ }
- public double getOvertimePay()
+ public double getOvertimePay()
+ {
+ return payWithOvertime;
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
{
- return payWithOvertime;
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "150.0";
+
+ boolean passed = getResults(expect, output, "Expected output from main", true);
+ assertTrue(passed);
+ }
}
- }
|Exercise| Check Your Understanding
@@ -165,47 +212,48 @@ The **this** variable can be used anywhere you would use an object variable. Yo
:practice: T
Consider the following class definitions.
-
+
.. code-block:: java
public class Pay
{
- private double pay;
-
- public Pay(double p)
- {
- pay = p;
- }
-
- public double getPay()
- {
- return pay;
- }
-
- public void calculatePayWithOvertime()
- {
- // this Pay object is passed to the Overtime constructor
- Overtime ot = new Overtime(this);
- pay = ot.getOvertimePay();
- }
+ private double pay;
+
+ public Pay(double p)
+ {
+ pay = p;
+ }
+
+ public double getPay()
+ {
+ return pay;
+ }
+
+ public void calculatePayWithOvertime()
+ {
+ // this Pay object is passed to the Overtime constructor
+ Overtime ot = new Overtime(this);
+ pay = ot.getOvertimePay();
+ }
}
public class Overtime
{
- private double payWithOvertime;
+ private double payWithOvertime;
- public Overtime(Pay p)
- {
- payWithOvertime = p.getPay() * 1.5;
- }
- public double getOvertimePay()
- {
- return payWithOvertime;
- }
+ public Overtime(Pay p)
+ {
+ payWithOvertime = p.getPay() * 1.5;
+ }
+
+ public double getOvertimePay()
+ {
+ return payWithOvertime;
+ }
}
The following code segment appears in a class other than Pay or Overtime.
-
+
.. code-block:: java
Pay one = new Pay(20.0);
@@ -213,30 +261,30 @@ The **this** variable can be used anywhere you would use an object variable. Yo
System.out.println(one.getPay());
What, if anything, is printed as a result of executing the code segment?
-
+
- 10.0
-
+
- The pay starts at 20 and then increases with overtime.
-
+
- 15.0
-
+
- If the pay started at 10, this would be the result.
-
+
- 20.0
-
+
- The pay starts at 20 and then increases with overtime.
-
+
- 30.0
-
+
+ Correct! The pay starts at 20 and then increases with overtime by multiplying by 1.5.
-
+
- Nothing is printed because the code will not compile.
-
+
- Incorrect. The code will compile.
-
-
+
+
|Groupwork| Programming Challenge : Bank Account
------------------------------------------------------------
@@ -244,29 +292,131 @@ The **this** variable can be used anywhere you would use an object variable. Yo
.. figure:: Figures/dollarSign.png
:width: 100px
:align: left
-
-- Create a class called BankAccount below that keeps track of the account holder's name, the account number, and the balance in the account. Make sure you use the appropriate data types for these.
-- Write 2 constructors for the class that initialize the instance variables to default values and to given parameters. For the parameters, use the same variable names as your instance variables. Use the **this** keyword to distinguish between the instance variables and the parameter variables.
+.. |ATM video| raw:: html
-- Write a toString() method for the class. Use the **this** keyword to return the instance variables.
+ video
-- Write a withdraw(amount) and deposit(amount) for the class. Withdraw should subtract the amount from the balance as long as there is enough money in the account (the balance is larger than the amount). Deposit should add the amount to the balance. Use the **this** keyword to refer to the balance.
-- Test your class below with a main method that creates a Bank Account object and calls its deposit and withdraw methods and prints out the object to test its toString() method.
+A bank account can be used to store your money. The bank keeps track of the account holder's name, the acount balance which is the amount of money in the account, and assigns an account number to each account. At the bank or an ATM (automatic teller machine) or on a phone app, the account holder can deposit (add) or withdraw (subtract) an amount from their account. Here's a |ATM video| that shows the steps to use an ATM to withdraw money from a bank acount. Phone apps like Venmo and Paypal connect to your bank account or credit card to send and get money from businesses or friends.
+
+For this challenge, you can work in pairs to:
+
+- Create a class called BankAccount below that keeps track of the account holder's name, the account number, and the balance in the account. Make sure you use the appropriate data types for these.
+
+- Write 2 constructors for the class: one that initializes all the instance variables and one that only has 2 parameters for the name and account number and initializes the balance to 0. For the parameters, use the same variable names as your instance variables. Use the ``this`` keyword to distinguish between the instance variables and the parameter variables.
+
+- Write a ``toString`` method for the class. Use the ``this`` keyword to return the instance variables.
+
+- Write ``withdraw(amount)`` and ``deposit(amount)`` methods for the class. The ``withdraw`` method should subtract the amount from the balance as long as there is enough money in the account (the balance is larger than the amount). And ``deposit`` should add the amount to the balance. Use the ``this`` keyword to refer to the balance.
+
+- Test your class below with a ``main`` method that creates a ``BankAccount`` object and calls its ``deposit`` and ``withdraw`` methods and prints out the object to test its ``toString`` method.
.. activecode:: challenge-5-9-BankAccount
:language: java
+ :autograde: unittest
- Create a class called BankAccount that keeps track of the account holder's name, the account number, and the balance in the account. Create 2 constructors, a toString() method, and withdraw(amount) and deposit(amount) methods. Test your class in a main method.
+ Create a class called BankAccount that keeps track of the account holder's name, the account number, and the balance in the account. Create 2 constructors, a toString() method, and withdraw(amount) and deposit(amount) methods. Use the this keyword in the constructor and methods. Test your class in a main method.
~~~~
- public class BankAccount
- {
-
-
- }
-
+ public class BankAccount {}
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("BankAccount");
+ }
+
+ @Test
+ public void test0()
+ {
+ String output = getMethodOutput("main");
+ String expect = "Something like:\nName 101 100.0\nName 101 200.0\nName 101 100.0";
+
+ boolean passed = !output.contains("Method main does not exist");
+
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ String output = checkConstructor(2);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking 2-parameter constructor");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ String output = checkConstructor(3);
+ String expect = "pass";
+
+ boolean passed = getResults(expect, output, "Checking 3-parameter constructor");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test01()
+ {
+ String expect = "3 Private";
+ String output = testPrivateInstanceVariables();
+
+ boolean passed = getResults(expect, output, "Checking Private Instance Variable(s)");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "public String toString()";
+
+ boolean passed = checkCodeContainsRegex("toString method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test41()
+ {
+ String target = "public void withdraw(*)";
+
+ boolean passed = checkCodeContainsRegex("withdraw method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test42()
+ {
+ String target = "public void deposit(*)";
+
+ boolean passed = checkCodeContainsRegex("deposit method", target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test5()
+ {
+ String target = "this.";
+ String code = getCode();
+
+ int num = countOccurences(code, target);
+
+ boolean passed = num >= 6;
+
+ getResults("6+", "" + num, "use of this.*", passed);
+ assertTrue(passed);
+ }
+ }
Summary
--------
@@ -277,7 +427,7 @@ Summary
- Static methods do not have a this reference.
-- The this variable can be used anywhere you would use an object variable, even to pass it to another method as an argument.
+- The this variable can be used anywhere you would use an object variable, even to pass it to another method as an argument.
AP Practice
@@ -287,14 +437,14 @@ AP Practice
:practice: T
Consider the following class definitions.
-
+
.. code-block:: java
-
+
public class Liquid
{
private int currentTemp;
- public Liquid (int ct)
+ public Liquid(int ct)
{
currentTemp = ct;
}
@@ -316,9 +466,9 @@ AP Practice
public LiquidJar()
{
- totalTemp = 0;
+ totalTemp = 0;
}
-
+
public void addLiquid(Liquid l)
{
totalTemp += l.getCurrentTemp();
@@ -332,7 +482,7 @@ AP Practice
}
Consider the following code segment, which appears in a class other than Liquid or LiquidJar.
-
+
.. code-block:: java
Liquid water = new Liquid(50);
@@ -346,26 +496,21 @@ AP Practice
What, if anything, is printed out after the execution of the code segment?
- 50
-
+
- The liquid water has a temperature of 50 but more is added to the jar.
-
+
- 15
-
+
- The liquid milk has a temperature of 15 but more is added to the jar.
- 65
-
- + Correct! The liquid water with a temperature of 50 and then the liquid milk with a temperature of 15 are added to the jar.
-
- - Nothing, the code segment attempts to access the private variable currentTemp outside of its scope.
-
- - Incorrect. The currentTemp is never used outside its scope.
-
- - Nothing, the code segment attempts to access the private variable totalTemp outside of its scope.
-
- - Incorrect. The totalTemp is never used outside its scope.
+ + Correct! The liquid water with a temperature of 50 and then the liquid milk with a temperature of 15 are added to the jar.
+ - Nothing, the code segment attempts to access the private variable currentTemp outside of its scope.
+ - Incorrect. The currentTemp is never used outside its scope.
+ - Nothing, the code segment attempts to access the private variable totalTemp outside of its scope.
+ - Incorrect. The totalTemp is never used outside its scope.
diff --git a/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst b/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst
new file mode 100644
index 000000000..702fc6a00
--- /dev/null
+++ b/_sources/Unit5-Writing-Classes/topic-parsons-practice.rst
@@ -0,0 +1,372 @@
+.. qnum::
+ :prefix: 5-18-
+ :start: 1
+
+Mixed Up Code Practice
+=========================================================
+
+Try to solve each of the following. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren't needed in the correct solution. Try to solve these on your phone or other mobile device!
+
+
+.. parsonsprob:: ch7ex1muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program segment should define a ``Dog`` class with a constructor that takes one parameter, ``name``, and sets the value of the Dog's private ``name`` attribute to that. There should also be a ``getName`` method which returns the ``name`` attribute of the ``Dog`` object. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Dog
+ {
+ =====
+ private String name;
+ =====
+ public String name; #paired: Instance variables should be encapsulated
+ =====
+ public Dog(String name)
+ {
+ =====
+ public Dog Dog(String name)
+ { #paired: Constructors never have a return type
+ =====
+ this.name = name;
+ =====
+ } // end constructor
+
+ public String getName()
+ {
+ =====
+ return this.name;
+ =====
+ } // end getName
+ } //end class
+
+.. parsonsprob:: ch7ex2muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program segment should define a ``Dog`` class with a constructor that takes two parameters: ``name`` (a String) and ``age`` (an integer). These parameters should be saved in correspondingly-named private instance variables. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Dog
+ {
+ =====
+ public class Dog #paired: Curly braces are required when declaring a class
+ =====
+ private String name;
+ private int age;
+ =====
+ public Dog(String name, int age)
+ {
+ =====
+ public Dog(name, age)
+ { #paired: Methods need to specify the types for arguments
+ =====
+ this.name = name;
+ this.age = age;
+ =====
+ name = name;
+ age = age; #paired: When the parameter name is the same as an attribute, you MUST use "this" to refer to the attribute
+ =====
+ } // end constructor
+ } // end class
+
+
+.. parsonsprob:: ch7ex3muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program segment should define a ``Cat`` class with a constructor that takes two parameters\: ``name`` (a String) and ``age`` (an integer). These parameters should be saved in correspondingly-named private attributes of ``Cat`` objects. Next, there should be a ``makeSound`` method that prints ``"meow"``. Finally, there should be a ``toString`` method that returns "Name\: name, Age\: age" (such that ``Cat("Lucky", 10)``'s ``toString`` method would return "Name\: Lucky, Age\: 10"). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Cat
+ {
+ =====
+ private String name;
+ private int age;
+
+ public Cat(String name, int age)
+ {
+ =====
+ this.name = name;
+ this.age = age;
+ =====
+ } // end constructor
+
+ public void makeSound()
+ {
+ =====
+ } // end constructor
+
+ public String makeSound()
+ { #paired: When a method returns nothing, its return type should be "void"
+ =====
+ System.out.println("meow");
+ =====
+ } // end makeSound
+
+ public String toString()
+ {
+ =====
+ return "Name: " + this.name + ", Age: " + this.age;
+ =====
+ } // end toString
+ } //end class
+
+.. parsonsprob:: ch7ex4muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program segment should define a ``Square`` class with a constructor that takes one parameter\: ``length`` (an integer). This parameter should be saved in a correspondingly-named private attribute of ``Square`` objects. The ``Square`` class should also have a variable ``numberOfSquares`` that tracks how many squares have been created. Finally, there should be a ``toString`` method which returns ``"Length: length"`` (such that ``Square(10)``'s toString method would return ``"Length: 10"``. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Square
+ {
+ =====
+ public static int numberOfSquares = 0;
+ private int length;
+ =====
+ private int numberOfSquares = 0;
+ private int length; #paired: When you need a variable to be accessible for every object of a class, it should be static
+ =====
+ public Square(int length)
+ {
+ =====
+ this.length = length;
+ numberOfSquares++;
+ =====
+ } // end constructor
+ =====
+ public String toString()
+ {
+ =====
+ return "Length: " + this.length;
+ =====
+ } // end toString
+ } //end class
+
+.. parsonsprob:: ch7ex5muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program segment should define a ``Rectangle`` class with a constructor that can take zero or two integer parameters. With zero arguments passed, the ``Rectangle`` should be initialized with a ``length`` of 10 and a ``width`` of 10. With two integers passed, the ``Rectangle`` should have a ``length`` equal to argument1 and a ``width`` equal to argument2. There should also be an ``getArea`` method that returns the area ``length`` times ``width``. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Rectangle
+ {
+ =====
+ private int length;
+ private int width;
+
+ public Rectangle()
+ {
+ =====
+ this.length = 10;
+ this.width = 10;
+ =====
+ } // end zero-argument constructor
+
+ public Rectangle(int length, int width)
+ {
+ =====
+ this.length = length;
+ this.width = width;
+ =====
+ } // end two-argument constructor
+
+ public int getArea()
+ {
+ =====
+ return this.length * this.width;
+ =====
+ } // end getArea
+ } // end class
+
+.. parsonsprob:: ch7ex6muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program should define a ``CelestialBody`` class. The class should have two instance variables: ``orbitLength`` and ``daysSinceDiscovered``. The ``orbitLength`` variable should be initialized through the constructor, while ``daysSinceDiscovered`` should be derived from ``orbitLength`` and the ``orbit`` method. The ``orbit(int numberOfTimes)`` should add ``orbitLength * numberOfTimes`` to ``daysSinceDiscovered`` (e.g., if Planet X has done two orbits with an orbit length of 12 days, it was discovered 24 days ago. If it then orbits another three times, it was discovered 60 days ago). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class CelestialBody
+ {
+ =====
+ private int orbitLength;
+ private int daysSinceDiscovered;
+ =====
+ public CelestialBody(int orbitLength)
+ {
+ =====
+ this.daysSinceDiscovered = 0;
+ this.orbitLength = orbitLength;
+ =====
+ this.orbitLength = orbitLength; #paired: daysSinceDiscovered needs to be initialized
+ =====
+ } // end constructor
+
+ public void orbit(int numberOfTimes)
+ {
+ =====
+ } // end constructor
+
+ public int orbit(int numberOfTimes)
+ { #paired: A method who returns nothing should have a void return type
+ =====
+ this.daysSinceDiscovered += this.orbitLength * numberOfTimes;
+ =====
+ } // end orbit
+ } // end class
+
+.. parsonsprob:: ch7ex7muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program should define a ``Person`` class. Each ``Person`` instance should have a String ``name`` attribute and a integer ``age`` attribute. There should also be ``getName`` and ``setName`` functions. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Person
+ {
+ =====
+ private String name;
+ private int age;
+
+ public Person(String name, int age)
+ {
+ =====
+ this.name = name;
+ this.age = age;
+ =====
+ } // end constructor
+
+ public String getName()
+ {
+ =====
+ return this.name;
+ =====
+ } // end getName
+
+ public void setName(String newName)
+ {
+ =====
+ this.name = newName;
+ =====
+ } // end setName
+ } // end class
+
+.. parsonsprob:: ch7ex8muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program should define a ``Point`` class. Each ``Point`` instance should have integer ``x`` and ``y`` attributes (there are associated ``getX`` and ``getY`` methods whose implementations aren't shown). There should be a ``getDistance`` method that takes in another ``Point`` object as an argument and calculates the distance from this object to that one (which would be sqrt((this.x - other.x) ^ 2 + (this.y - other.y) ^ 2)). But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Point
+ {
+ =====
+ private int x;
+ private int y;
+
+ public Point(int x, int y)
+ {
+ =====
+ this.x = x;
+ this.y = y;
+ =====
+ } // end constructor
+
+ public double getDistance(Point other)
+ {
+ =====
+ return Math.sqrt(Math.pow(this.x - other.getX(), 2) + Math.pow(this.y - other.getY(), 2));
+ =====
+ return Math.sqrt((this.x - other.getX()) ** 2 + (this.y - other.getY()) ** 2); #paired: Exponents in java should use Math.pow
+ =====
+ } // end getDistance
+ } // end class
+
+.. parsonsprob:: ch7ex9muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program should define an ``Account`` class. Each ``Account`` instance should have integer ``balance`` and String ``owner`` attributes (and the constructor should take those in that order). To decrease ``balance``, there should be a ``withdraw`` method that takes in an integer argument and subtracts that from ``balance``. However, if ``balance`` would end as a negative number, it should just be set to zero. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+ -----
+ public class Account
+ {
+ =====
+ private int balance;
+ private String owner;
+
+ public Account(int balance, String owner)
+ {
+ =====
+ this.balance = balance;
+ this.owner = owner;
+ =====
+ } // end constructor
+
+ public void withdraw(int amount)
+ {
+ =====
+ if (amount > this.balance)
+ {
+ =====
+ this.balance = 0;
+ =====
+ } // end if
+
+ else {
+ =====
+ this.balance -= amount;
+ =====
+ } // end else
+ =====
+ } // end withdraw
+ } // end class
+
+.. parsonsprob:: ch7ex10muc
+ :numbered: left
+ :practice: T
+ :adaptive:
+ :noindent:
+
+ The following program should define a ``Character`` class. Each ``Character`` instance should have a integer ``healthPoints`` attribute and a String ``name`` attribute. There is a constructor and ``getHP``, ``setHP``, and ``getName`` methods that are not shown. Finally, there needs to be a ``fight(Character other)`` method that lets a character fight another. If the character's ``healthPoints`` are the same or more than ``other``'s, ``other``'s HP should be set to zero, the current character's HP should be set to the difference, and the program should print “{the character's name} wins”. If ``other``'s HP is greater, the current character's HP should be set to zero, ``other``'s HP should be set to the difference, and the program should print “{other’s name} wins”. But the blocks have been mixed up and include pairs of lines where one is unneeded. Drag the necessary code from the left to the right and put them in order so that the code would work correctly. Click the Check button to check your solution.
+
+ -----
+ public class Character
+ {
+ =====
+ // instance variables, constructor, & getter/setters not shown
+ =====
+ public void fight(Character other)
+ {
+ =====
+ if (this.getHP() >= other.getHP())
+ {
+ =====
+ this.setHP(this.getHP() - other.getHP());
+ other.setHP(0);
+ System.out.println(this.getName() + " wins");
+ =====
+ } // end if
+ =====
+ else
+ {
+ =====
+ other.setHP(other.getHP() - this.getHP());
+ this.setHP(0);
+ System.out.println(other.getName() + " wins");
+ =====
+ } // end else
+ =====
+ } // end fight
+ } // end class
diff --git a/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst b/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst
new file mode 100644
index 000000000..e774fe6c2
--- /dev/null
+++ b/_sources/Unit5-Writing-Classes/topic-toggle-problems.rst
@@ -0,0 +1,51 @@
+.. qnum::
+ :prefix: 5-18-
+ :start: 1
+
+Toggle Mixed Up or Write Code Practice
+=========================================================
+
+ For each of the problems below, if you need help, you can pull down the toggle menu to choose the associated mixed up code problem to help you get started.
+
+For the mixed up code problems, drag the blocks into the correct order. Click the *Check Me* button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems may have an extra block that isn't needed in the correct solution. After 3 tries, you can ask for help and some of the blocks will be combined. You can solve these on your phone or other mobile device!
+
+
+.. selectquestion:: select_u5_muc_wc1
+ :fromid: u5_muc_wc1, ch7ex1muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc2
+ :fromid: u5_muc_wc2, ch7ex2muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc3
+ :fromid: u5_muc_wc3, ch7ex3muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc4
+ :fromid: u5_muc_wc4, ch7ex4muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc5
+ :fromid: u5_muc_wc5, ch7ex5muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc6
+ :fromid: u5_muc_wc6, ch7ex6muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc7
+ :fromid: u5_muc_wc7, ch7ex7muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc8
+ :fromid: u5_muc_wc8, ch7ex8muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc9
+ :fromid: u5_muc_wc9, ch7ex9muc
+ :toggle: lock
+
+.. selectquestion:: select_u5_muc_wc10
+ :fromid: u5_muc_wc10, ch7ex10muc
+ :toggle: lock
diff --git a/_sources/Unit6-Arrays/6-1-images/China.jpg b/_sources/Unit6-Arrays/6-1-images/China.jpg
index 2b8f71ffd..29f294c0f 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/China.jpg and b/_sources/Unit6-Arrays/6-1-images/China.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/Egypt.jpg b/_sources/Unit6-Arrays/6-1-images/Egypt.jpg
index 38f4b548c..d57a93662 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/Egypt.jpg and b/_sources/Unit6-Arrays/6-1-images/Egypt.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/France.jpg b/_sources/Unit6-Arrays/6-1-images/France.jpg
index f541ab99a..372bbf472 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/France.jpg and b/_sources/Unit6-Arrays/6-1-images/France.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/Germany.jpg b/_sources/Unit6-Arrays/6-1-images/Germany.jpg
index d99b4382c..84bd1c259 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/Germany.jpg and b/_sources/Unit6-Arrays/6-1-images/Germany.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/India.jpg b/_sources/Unit6-Arrays/6-1-images/India.jpg
index 044a587c0..b5a59a400 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/India.jpg and b/_sources/Unit6-Arrays/6-1-images/India.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/Kenya.jpg b/_sources/Unit6-Arrays/6-1-images/Kenya.jpg
index 5cf70e051..950bb099f 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/Kenya.jpg and b/_sources/Unit6-Arrays/6-1-images/Kenya.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/Map images.zip b/_sources/Unit6-Arrays/6-1-images/Map images.zip
deleted file mode 100644
index 620140f77..000000000
Binary files a/_sources/Unit6-Arrays/6-1-images/Map images.zip and /dev/null differ
diff --git a/_sources/Unit6-Arrays/6-1-images/Mexico.jpg b/_sources/Unit6-Arrays/6-1-images/Mexico.jpg
index 9df5cf55c..8a2c2dfa2 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/Mexico.jpg and b/_sources/Unit6-Arrays/6-1-images/Mexico.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/US.jpg b/_sources/Unit6-Arrays/6-1-images/US.jpg
index 87b02a252..a6f4b0ba1 100644
Binary files a/_sources/Unit6-Arrays/6-1-images/US.jpg and b/_sources/Unit6-Arrays/6-1-images/US.jpg differ
diff --git a/_sources/Unit6-Arrays/6-1-images/africa.png b/_sources/Unit6-Arrays/6-1-images/africa.png
new file mode 100644
index 000000000..3f335e5ef
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/africa.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/americas.png b/_sources/Unit6-Arrays/6-1-images/americas.png
new file mode 100644
index 000000000..036187e49
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/americas.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/asia-pacific.png b/_sources/Unit6-Arrays/6-1-images/asia-pacific.png
new file mode 100644
index 000000000..3b72622df
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/asia-pacific.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/central-america.png b/_sources/Unit6-Arrays/6-1-images/central-america.png
new file mode 100644
index 000000000..9be8093fa
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/central-america.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/europe.png b/_sources/Unit6-Arrays/6-1-images/europe.png
new file mode 100644
index 000000000..271c9e2dd
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/europe.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/middle-east.png b/_sources/Unit6-Arrays/6-1-images/middle-east.png
new file mode 100644
index 000000000..c7241cdca
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/middle-east.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/north-america.png b/_sources/Unit6-Arrays/6-1-images/north-america.png
new file mode 100644
index 000000000..cd340b12b
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/north-america.png differ
diff --git a/_sources/Unit6-Arrays/6-1-images/south-america.png b/_sources/Unit6-Arrays/6-1-images/south-america.png
new file mode 100644
index 000000000..ec931101f
Binary files /dev/null and b/_sources/Unit6-Arrays/6-1-images/south-america.png differ
diff --git a/_sources/Unit6-Arrays/ArrayParsonsPractice.rst b/_sources/Unit6-Arrays/ArrayParsonsPractice.rst
index 81fbdd2df..b6d8a2088 100644
--- a/_sources/Unit6-Arrays/ArrayParsonsPractice.rst
+++ b/_sources/Unit6-Arrays/ArrayParsonsPractice.rst
@@ -7,36 +7,37 @@ 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
+.. parsonsprob:: arrayex1muc
:numbered: left
:practice: T
: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[] scores = null;
@@ -35,10 +35,10 @@ These problems are easier than most of those that you will usually see on the AP
: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.
+ :feedback_e: You can declare and array and create it in the same statement. Use the new operator to create the array and specify the size in square brackets.
Which of the following declarations will cause a compile time error?
-
+
.. mchoice:: qaeasy_3
:practice: T
:answer_a: 1
@@ -48,13 +48,13 @@ These problems are easier than most of those that you will usually see on the AP
: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_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}``?
-
+ What is returned from ``arr[3]`` if ``arr={6, 3, 1, 2}``?
+
.. mchoice:: qaeasy_4
:practice: T
:answer_a: 17.5
@@ -63,26 +63,26 @@ These problems are easier than most of those that you will usually see on the AP
: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.
+ :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;
+ 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 b[0]
:feedback_e: b[0] can be any value, so long as no other array element is equal to it.
- Which of the following statements is a valid conclusion. Assume that variable ``b`` is an array of ``k`` integers and that the following is true:
-
+ Which of the following statements is a valid conclusion. Assume that variable ``b`` is an array of ``k`` integers and that the following is true:
+
.. code-block:: java
b[0] != b[i] for all i from 1 to k-1
@@ -211,29 +211,30 @@ These problems are similar to those you will see on the AP CS A exam.
:correct: c
:feedback_a: It is the last value in a that controls the final state of temp, as the loop is progressing through the array from 0 to the end.
:feedback_b: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false.
- :feedback_c: Because each time through the loop temp is reset, it will only be returned as true if the last value in a is equal to val.
+ :feedback_c: Because each time through the loop temp is reset, it will only be returned as true if the last value in a is equal to val.
:feedback_d: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false, so it is possible for just the last value to be equal to val.
:feedback_e: Because temp is reset every time through the loop, only the last element controls whether the final value is true or false, so it is possible for several elements to be equal to val.
Consider the following code segment. Which of the following statements best describes the condition when it returns true?
-
+
.. code-block:: java
boolean temp = false;
- for (int i = 0; i < a.length; i++) {
+ for (int i = 0; i < a.length; i++)
+ {
temp = (a[i] == val);
}
return temp;
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-2 target in nums
- :answer_b: It is the length of the array nums
- :answer_c: It is the length of the first consecutive block of the value target in nums
- :answer_d: It is the number of occurrences of the value target in nums
- :answer_e: It is the length of the last consecutive block of the value target in nums
+ :answer_a: It is the length of the shortest consecutive block of the value target in nums
+ :answer_b: It is the length of the array nums
+ :answer_c: It is the length of the first consecutive block of the value target in nums
+ :answer_d: It is the number of occurrences of the value target in nums
+ :answer_e: It is the length of the last consecutive block of the value target in nums
:correct: d
:feedback_a: It doesn't reset lenCount ever, so it just counts all the times the target value appears in the array.
:feedback_b: The only count happens when lenCount is incremented when nums[k] == target. nums.length is only used to stop the loop.
@@ -242,27 +243,32 @@ You can step through the code above with the Java Visualizer by clicking the fol
:feedback_e: It doesn't reset lenCount ever, so it just counts all the times the target value appears in the array.
Consider the following data field and method ``findLongest``. Method ``findLongest`` is intended to find the longest consecutive block of the value ``target`` occurring in the array ``nums``; however, ``findLongest`` does not work as intended. For example given the code below the call ``findLongest(10)`` should return 3, the length of the longest consecutive block of 10s. Which of the following best describes the value actually returned by a call to ``findLongest``?
-
+
.. code-block:: java
private int[] nums = {7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10};
-
- public int findLongest(int target) {
+
+ public int findLongest(int target)
+ {
int lenCount = 0; // length of current consecutive numbers
- int maxLen = 0; // max length of consecutive numbers
- for (int k = 0; k < nums.length; k++) {
- if (nums[k] == target) {
+ int maxLen = 0; // max length of consecutive numbers
+ for (int k = 0; k < nums.length; k++)
+ {
+ if (nums[k] == target)
+ {
lenCount++;
- } else if (lenCount > maxLen) {
+ } else if (lenCount > maxLen)
+ {
maxLen = lenCount;
}
}
- if (lenCount > maxLen) {
+ if (lenCount > maxLen)
+ {
maxLen = lenCount;
}
return maxLen;
}
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-3 num and returns from mystery the first time that the condition is encountered. The values are not ordered so we don't know if this is the largest value smaller than n.
Consider the following data field and method. Which of the following best describes the contents of ``myStuff`` in terms of ``m`` and ``n`` after the following statement has been executed?
-
+
.. code-block:: java
private int[] myStuff;
//precondition: myStuff contains
// integers in no particular order
- public int mystery(int num) {
- for (int k = myStuff.length - 1; k >= 0; k--) {
- if (myStuff[k] < num) {
+ public int mystery(int num)
+ {
+ for (int k = myStuff.length - 1; k >= 0; k--)
+ {
+ if (myStuff[k] < num)
+ {
return k;
}
}
@@ -297,7 +306,7 @@ You can step through the code above with the Java Visualizer by clicking the fol
}
int m = mystery(n)
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-4 k loops from 0 to arr.length - 1. So it checks all of the elements in the array.
Consider the following field ``arr`` and method ``checkArray``. Which of the following best describes what ``checkArray`` returns?
-
+
.. code-block:: java
private int[] arr;
@@ -334,63 +343,63 @@ You can step through the code above with the Java Visualizer by clicking the fol
}
return loc;
}
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-5 return (a[1] *= 2);, which would change the value at a[1].
- :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to 2. The return (a[1] * 2) does not change the value at a[1].
- :feedback_c: This would be true if array indicies started at 1 instead of 0 and if the code changed the value at index 1 to the current value times two.
- :feedback_d: This would be true if array indices started at 1 rather than 0.
+ :feedback_a: This would be true if it was return (a[1] *= 2);, which would change the value at a[1].
+ :feedback_b: The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to 2. The return (a[1] * 2) does not change the value at a[1].
+ :feedback_c: This would be true if array indices started at 1 instead of 0 and if the code changed the value at index 1 to the current value times two.
+ :feedback_d: This would be true if array indices started at 1 rather than 0.
:feedback_e: This can't be true because a[1]--; means the same as a[1] = a[1] - 1; so the 3 changes to 2. Parameters are all pass by value in Java which means that a copy of the value is passed to a method. But, since an array is an object a copy of the value is a copy of the reference to the object. So changes to objects in methods are permanent.
-
+
Given the following field and method declaration, what is the value in ``a[1]`` when ``m1(a)`` is run?
-
+
.. code-block:: java
- int[] a = {7, 3, -1};
+ int[] a = {7, 3, -1};
+
+ public static int m1(int[] a)
+ {
+ a[1]--;
+ return (a[1] * 2);
+ }
- public static int m1(int[] a)
- {
- a[1]--;
- return (a[1] * 2);
- }
-
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-6 k is reached as long as arr[i] < someValue is true. The last time the loop executes, i will equal k-1, if the condition is always true. The number of times a loop executes is equal to the largest value when the loop executes minus the smallest value plus one. In this case that is (k - 1) - 1 + 1 which equals k - 1.
+ :feedback_a: This loop will start at 1 and continue until k is reached as long as arr[i] < someValue is true. The last time the loop executes, i will equal k-1, if the condition is always true. The number of times a loop executes is equal to the largest value when the loop executes minus the smallest value plus one. In this case that is (k - 1) - 1 + 1 which equals k - 1.
:feedback_b: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1 and continued while it was less than or equal to k.
- :feedback_c: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1.
+ :feedback_c: This would be true if arr[i] < someValue was always true and the loop started at 0 instead of 1.
:feedback_d: This would be the case if only one element in the array would fulfill the condition that arr[i] < someValue.
- :feedback_e: This is the minimum number of times that HELLO could be executed. This would be true if k was less than i initially.
+ :feedback_e: This is the minimum number of times that HELLO could be executed. This would be true if k was less than i initially.
Consider the following code. What is the *maximum* amount of times that ``HELLO`` could possibly be printed?
.. code-block:: java
-
- for (int i = 1; i < k; i++)
+
+ for (int i = 1; i < k; i++)
{
- if (arr[i] < someValue)
+ if (arr[i] < someValue)
{
System.out.print("HELLO")
}
}
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-7 data.length - 1. Notice the for-loop indexing.
:feedback_d: The indexing of this method is correct. The for-loop begins at the last valid index and ends when k is equal to 0, and the method does not access any values other than the ones specified.
:feedback_e: This method starts at the last valid index of the array and adds the value of the previous element to the element at index k - 1.
-
+
Consider the following method ``changeArray``. An array is created that contains ``{2, 8, 10, 9, 6}`` and is passed to ``changeArray``. What are the contents of the array after the ``changeArray`` method executes?
.. code-block:: java
@@ -416,7 +425,7 @@ You can step through the code above with the Java Visualizer by clicking the fol
for (int k = data.length - 1; k > 0; k--)
data[k - 1] = data[k] + data[k - 1];
}
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-8 i started at 0 instead of arr1.length / 2.
+ :feedback_a: This would be true if i started at 0 instead of arr1.length / 2.
:feedback_b: This would be true if i started at 0 and ended when it reached arr1.length / 2.
:feedback_c: This loop starts at arr2.length / 2 which is 2 and loops to the end of the array copying from arr2 to arr1.
- :feedback_d: This would be correct if this loop didn't change arr1, but it does.
- :feedback_e: This would be correct if it set arr1[i] equal to arr[i] + arr[2] instead.
-
+ :feedback_d: This would be correct if this loop didn't change arr1, but it does.
+ :feedback_e: This would be correct if it set arr1[i] equal to arr[i] + arr[2] instead.
+
Assume that ``arr1={1, 5, 3, -8, 6}`` and ``arr2={-2, -1, -5, 3, -4}`` what will the contents of ``arr1`` be after ``copyArray`` finishes executing?
.. code-block:: java
@@ -444,7 +453,7 @@ You can step through the code above with the Java Visualizer by clicking the fol
arr1[i] = arr2[i];
}
}
-
+
You can step through the code above with the Java Visualizer by clicking the following link `Prob-7-10-9 temp will not cause the infinite loop.
Given the following code segment, which of the following will cause an infinite loop? Assume that ``temp`` is an ``int`` variable initialized to be greater than zero and that ``a`` is an array of ints.
-
- .. code-block:: java
+
+ .. code-block:: java
for ( int k = 0; k < a.length; k++ )
{
@@ -472,49 +481,15 @@ You can step through the code above with the Java Visualizer by clicking the fol
a[ k ] *= 2;
}
}
-
-You can step through the code above using the Java Visualizer by clicking on the following link `Prob-7-10-10 sum <= limit.
+
+ What is the value of ``i`` after the following code executes?
+
.. code-block:: java
-
+
int[] x = {2, 1, 4, 5, 7};
int limit = 7;
int i = 0;
@@ -279,7 +282,7 @@ Click the "Start" button when you are ready to begin the exam, but only then as
sum += x[i];
i++;
}
-
+
.. mchoice:: arrayEx8
:practice: T
:answer_a: for (int j=0 ; j < x.length; j++)
@@ -290,10 +293,10 @@ Click the "Start" button when you are ready to begin the exam, but only then as
:feedback_a: The inner loop should start at the outer loop current position plus one to not double count inversions.
:feedback_b: The inner loop should start at the outer loop current position plus one to not double count inversions.
:feedback_c: This correctly starts at the outer loop current index plus one and loops through the rest of the array.
- :feedback_d: This misses checking the last value in the array since it is j < x.length-1.
-
- If any two numbers in an array of integers, not necessarily consecutive numbers in the array, are out of order (i.e. the number that occurs first in the array is larger than the number that occurs second), then that is called an inversion. For example, consider an array “x” that has the values {1, 4, 3, 2}. Then there are three inversions since 4 is greater than both 3 and 2 and 3 is greater than 2. Which of the following can be used to replace the missing code so that the code correctly counts the number of inversions?
-
+ :feedback_d: This misses checking the last value in the array since it is j < x.length-1.
+
+ If any two numbers in an array of integers, not necessarily consecutive numbers in the array, are out of order (i.e. the number that occurs first in the array is larger than the number that occurs second), then that is called an inversion. For example, consider an array ``x`` that has the values {1, 4, 3, 2}. Then there are three inversions since 4 is greater than both 3 and 2 and 3 is greater than 2. Which of the following can be used to replace the missing code so that the code correctly counts the number of inversions?
+
.. code-block:: java
@@ -306,8 +309,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as
inversionCount++;
}
}
-
-
+
+
.. mchoice:: arrayEx9
:practice: T
:answer_a: A
@@ -315,16 +318,16 @@ Click the "Start" button when you are ready to begin the exam, but only then as
:answer_c: C
:answer_d: D
:correct: b
- :feedback_a: This increments a2 before copying the value into array2 and so puts it in the wrong place.
+ :feedback_a: This increments a2 before copying the value into array2 and so puts it in the wrong place.
:feedback_b: This will copy all the even values in array1 to array2 and put them in the same position as they were in array1.
:feedback_c: This will cause an out of bounds error.
- :feedback_d: This increments a2 before copying the value into array2 and so puts it in the wrong place.
+ :feedback_d: This increments a2 before copying the value into array2 and so puts it in the wrong place.
+
+ Which of the following correctly copies all the even numbers from ``array1`` to ``array2`` in the same order as they are in ``array1`` without any errors? Assume that ``array2`` is large enough for all the copied values.
- Which of the following correctly copies all the even numbers from ``array1`` to ``array2`` in the same order as they are in ``array1`` without any errors? Assume that ``array2`` is large enough for all the copied values.
-
.. code-block:: java
-
- A.
+
+ A.
int a2 = 0;
for (int a1=0 ; a1 < array1.length ; a1++)
{
@@ -337,8 +340,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as
array2[a2] = array1[a1];
}
}
-
- B.
+
+ B.
int a2 = 0;
for (int a1=0 ; a1 < array1.length ; a1++)
{
@@ -351,8 +354,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as
a2++;
}
}
-
- C.
+
+ C.
int a2 = 0;
for ( int a1=0 ; a1 <= array1.length ; a1++)
{
@@ -365,8 +368,8 @@ Click the "Start" button when you are ready to begin the exam, but only then as
a2++;
}
}
-
- D.
+
+ D.
int a2 = 0;
for (int a1=0 ; a1 <= array1.length ; a1++)
{
@@ -380,7 +383,7 @@ Click the "Start" button when you are ready to begin the exam, but only then as
}
}
-
+
.. mchoice:: arrayEx10
:practice: T
:answer_a: {4, 3, 0, 0}
@@ -388,15 +391,15 @@ Click the "Start" button when you are ready to begin the exam, but only then as
:answer_c: {2, 4, 3, 0}
:answer_d: {2, 4, 1, 3}
:correct: a
- :feedback_a: This copies the value from array1[a1] to array2[a2] but only if the value at array1[a1] is greater than or equal to 2. So it copies the 4 and 3. Notice that a2 starts at 0 and a1 starts at 1.
- :feedback_b: This would be true except that a2 is only incremented if the copy occurs.
- :feedback_c: Walk through the very first iteration of the loop and notice that after the first iteration the first value in array2 is 4.
- :feedback_d: This would be true if we were asking for the values in array1.
+ :feedback_a: This copies the value from array1[a1] to array2[a2] but only if the value at array1[a1] is greater than or equal to 2. So it copies the 4 and 3. Notice that a2 starts at 0 and a1 starts at 1.
+ :feedback_b: This would be true except that a2 is only incremented if the copy occurs.
+ :feedback_c: Walk through the very first iteration of the loop and notice that after the first iteration the first value in array2 is 4.
+ :feedback_d: This would be true if we were asking for the values in array1.
After the following code executes what are the values in ``array2``?
-
+
.. code-block:: java
-
+
int[] array1 = {2, 4, 1, 3};
int[] array2 = {0, 0, 0, 0};
int a2 = 0;
@@ -408,5 +411,3 @@ Click the "Start" button when you are ready to begin the exam, but only then as
a2++;
}
}
-
-
\ No newline at end of file
diff --git a/_sources/Unit6-Arrays/horseBarnA.rst b/_sources/Unit6-Arrays/horseBarnA.rst
index fd587cb83..1c7f34bdd 100644
--- a/_sources/Unit6-Arrays/horseBarnA.rst
+++ b/_sources/Unit6-Arrays/horseBarnA.rst
@@ -5,20 +5,20 @@
Free Response - Horse Barn A
-------------------------------
-.. index::
- single: horse barn
+.. index::
+ single: horse barn
single: free response
-
-The following FRQ is a great example of working with an array of objects. It is a variation of part a of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
-The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CS A exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have.
+The following FRQ is a great example of working with an array of objects. It is a variation of part a of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
-
+The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CSA exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have.
-**Question 3.** Consider a software system that models a horse barn.
-.. code-block:: java
+**Question 3.** Consider a software system that models a horse barn.
+
+
+.. code-block:: java
public class Horse
{
@@ -29,36 +29,40 @@ The original question had an interface called Horse, but the problem below has b
/** @return the horse's weight */
public int getWeight()
{ implementation not shown }
-
+
// There may be other methods that are not shown
-
+
}
Another class called HorseBarn consists of N numbered spaces where each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N - 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below.
-.. code-block:: java
+.. 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) */ }
+ /**
+ * The spaces in the barn. Each array element holds a reference to the horse
+ * that is currently occupying the space. A null value indicates an empty
+ * space.
+ */
+ private Horse[] spaces;
+
+ /**
+ * Returns the index of the space that contains the horse with the specified
+ * name. Precondition: No two horses in the barn have the same name.
+ *
+ * @param name the name of the horse to find
+ * @return the index of the space containing the horse with the specified name;
+ * -1 if no horse with the specified name is in the barn.
+ */
+ public int findHorseSpace(String name)
+ {
+ /* to be implemented in part (a) */
+ }
}
-
+
**Part a.** Write the HorseBarn method findHorseSpace. This method returns the index of the space in which the horse with the specified name is located. If there is no horse with the specified name in the barn, the method returns -1.
.. figure:: Figures/horseBarnA.png
@@ -67,126 +71,250 @@ Another class called HorseBarn consists of N numbered spaces where each space ca
:figclass: align-center
Figure 1: Example calls and results
-
+
How to solve this problem
===========================
In order to find the index of the horse with the same name we are looking for, we will need to loop through the array ``spaces``. As we loop, we will compare the name we are looking for with the ``Horse`` object's name at the current index.
-We will have to watch out for spaces that are empty (are null).
-
-.. 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?
-
+We will have to watch out for spaces that are empty (are null). Click to reveal a practice problem about objects.
+
+.. reveal:: frhba_r1
+ :showtitle: Reveal Problem
+ :hidetitle: Hide Problem
+ :optional:
+
+ .. mchoice:: frhba_1
+ :answer_a: spaces[index].name;
+ :answer_b: spaces[index].getName();
+ :answer_c: spaces.get(index).getName();
+ :correct: b
+ :feedback_a: Getter methods are needed to access private class variables.
+ :feedback_b: This is the syntax for getting the value of an element in an array.
+ :feedback_c: This is the syntax for getting the value of an element in an arrayList.
+
+ Which of the following correctly retrieves the name of a "Horse" object from the "spaces" array?
+
+Once we have the name of the current ``Horse`` object, we need to compare this name to the name we are looking for. Click to reveal a practice problem about String comparisons.
+
+.. reveal:: frhba_r2
+ :showtitle: Reveal Problem
+ :hidetitle: Hide Problem
+ :optional:
+
+ .. mchoice:: frhba_2
+ :answer_a: str.compareTo(anotherString);
+ :answer_b: str == anotherString;
+ :answer_c: str.equals(anotherString);
+ :correct: c
+ :feedback_a: This String method is used for comparing two strings alphabetically. It returns 0 if they are equal so you would need to check the return value.
+ :feedback_b: This would only return true if the two variables refer to the same object.
+ :feedback_c: This String method will compare the characters in both strings and return true if they are the same.
+
+ What is the best way to compare two strings for equality?
+
Try It!
========
-
+
Try to write the code for the method ``findHorseSpace`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution. There are 3 tests so if you only see output for 1 or 2 check for errors below the code.
-
+
.. activecode:: lcfrhba1
:language: java
-
+ :autograde: unittest
+
+ FRQ HorseBarn A: Write the method findHorseSpace.
+ ~~~~
class Horse
{
- private String name;
- private int weight;
-
- public Horse(String theName, int theWeight)
- {
- this.name = theName;
- this.weight = theWeight;
- }
-
- public String getName() { return this.name;}
-
- public int getWeight() { return this.weight; }
-
- public String toString()
- {
- return "name: " + this.name + " weight: " + this.weight;
- }
+ private String name;
+ private int weight;
+
+ public Horse(String theName, int theWeight)
+ {
+ this.name = theName;
+ this.weight = theWeight;
+ }
+
+ public String getName()
+ {
+ return this.name;
+ }
+
+ public int getWeight()
+ {
+ return this.weight;
+ }
+
+ public String toString()
+ {
+ return "name: " + this.name + " weight: " + this.weight;
+ }
+ }
+
+ public class HorseBarn
+ {
+ private Horse[] spaces;
+
+ /**
+ * Constructor that takes the number of stalls
+ *
+ * @param numStalls - the number of stalls in the barn
+ */
+ public HorseBarn(int numStalls)
+ {
+ spaces = new Horse[numStalls];
+ }
+
+ /**
+ * Returns the index of the space that contains the horse with the specified
+ * name. * Precondition: No two horses in the barn have the same name.
+ *
+ * @param name the name of the horse to find
+ * @return the index of the space containing the horse with the specified name;
+ * -1 if no horse with the specified name is in the barn.
+ */
+ public int findHorseSpace(String name) {}
+
+ public String toString()
+ {
+ String result = "";
+ Horse h = null;
+ for (int i = 0; i < spaces.length; i++)
+ {
+ h = spaces[i];
+ result = result + "space " + i + " has ";
+ if (h == null)
+ {
+ result = result + " null \n";
+ }
+ else
+ {
+ result = result + h.toString() + "\n";
+ }
+ }
+ return result;
+ }
+
+ public static void main(String[] args)
+ {
+ HorseBarn barn = new HorseBarn(7);
+ barn.spaces[0] = new Horse("Trigger", 1340);
+ barn.spaces[2] = new Horse("Silver", 1210);
+ barn.spaces[3] = new Horse("Lady", 1575);
+ barn.spaces[5] = new Horse("Patches", 1350);
+ barn.spaces[6] = new Horse("Duke", 1410);
+
+ // print out what is in the barn
+ System.out.println(barn);
+
+ // test
+ System.out.println(
+ "Index of Trigger should be 0 and is "
+ + barn.findHorseSpace("Trigger"));
+ System.out.println(
+ "Index of Silver should be 2 and is "
+ + barn.findHorseSpace("Silver"));
+ System.out.println(
+ "Index of Coco should be -1 and is "
+ + barn.findHorseSpace("Coco"));
+ }
}
-
- public class HorseBarn
- {
- private Horse[] spaces;
-
- /** Constructor that takes the number of stalls
- * @param numStalls - the number of stalls in the barn
- */
- public HorseBarn(int numStalls)
- {
- spaces = new Horse[numStalls];
- }
-
- /** Returns the index of the space that contains the horse with the specified name.
- * * Precondition: No two horses in the barn have the same name.
- * @param name the name of the horse to find
- * @return the index of the space containing the horse with the specified name;
- * -1 if no horse with the specified name is in the barn.
- */
- public int findHorseSpace(String name)
- {
-
- }
-
- public String toString()
- {
- String result = "";
- Horse h = null;
- for (int i = 0; i < spaces.length; i++) {
- h = spaces[i];
- result = result + "space " + i + " has ";
- if (h == null) result = result + " null \n";
- else result = result + h.toString() + "\n";
- }
- return result;
- }
-
- public static void main (String[] args)
- {
- HorseBarn barn = new HorseBarn(7);
- barn.spaces[0] = new Horse("Trigger", 1340);
- barn.spaces[2] = new Horse("Silver",1210);
- barn.spaces[3] = new Horse("Lady", 1575);
- barn.spaces[5] = new Horse("Patches", 1350);
- barn.spaces[6] = new Horse("Duke", 1410);
-
- // print out what is in the barn
- System.out.println(barn);
-
- // test
- System.out.println("Index of Trigger should be 0 and is " +
- barn.findHorseSpace("Trigger"));
- System.out.println("Index of Silver should be 2 and is " +
- barn.findHorseSpace("Silver"));
- System.out.println("Index of Coco should be -1 and is " +
- barn.findHorseSpace("Coco"));
- }
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.lang.reflect.Field;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "Index of Trigger should be 0 and is 0\n"
+ + "Index of Silver should be 2 and is 2\n"
+ + "Index of Coco should be -1 and is -1";
+
+ boolean passed = removeSpaces(output).contains(removeSpaces(expect));
+
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ HorseBarn barn = new HorseBarn(7);
+
+ try
+ {
+ Field barnField = HorseBarn.class.getDeclaredField("spaces");
+ barnField.setAccessible(true);
+
+ Horse[] spaces = (Horse[]) barnField.get(barn);
+
+ spaces[1] = new Horse("Trigger", 1340);
+ spaces[3] = new Horse("Silver", 1210);
+ spaces[4] = new Horse("Lady", 1575);
+ spaces[6] = new Horse("Patches", 1350);
+ spaces[0] = new Horse("Duke", 1410);
+
+ String expected = "3";
+ String actual = "" + barn.findHorseSpace("Silver");
+
+ String msg =
+ "Checking findHorseSpace(\"Silver\") with [\"Duke\", \"Trigger\", null,"
+ + " \"Silver\", \"Lady\", null, \"Patches\"]";
+ boolean passed = getResults(expected, actual, msg);
+ assertTrue(passed);
+
+ }
+ catch (Exception e)
+ {
+ getResults("", "", "There was a error with the testing code.", false);
+ fail();
+ }
+ }
+
+ @Test
+ public void test2()
+ {
+ HorseBarn barn = new HorseBarn(7);
+
+ try
+ {
+ Field barnField = HorseBarn.class.getDeclaredField("spaces");
+ barnField.setAccessible(true);
+
+ Horse[] spaces = (Horse[]) barnField.get(barn);
+
+ spaces[1] = new Horse("Trigger", 1340);
+ spaces[3] = new Horse("Silver", 1210);
+ // spaces[4] = new Horse("Lady", 1575);
+ spaces[6] = new Horse("Patches", 1350);
+ spaces[0] = new Horse("Duke", 1410);
+
+ String expected = "-1";
+ String actual = "" + barn.findHorseSpace("Lady");
+
+ String msg =
+ "Checking findHorseSpace(\"Lady\") with [\"Duke\", \"Trigger\", null,"
+ + " \"Silver\", null, null, \"Patches\"]";
+ boolean passed = getResults(expected, actual, msg);
+ assertTrue(passed);
+
+ }
+ catch (Exception e)
+ {
+ getResults("", "", "There was a error with the testing code.", false);
+ fail();
+ }
+ }
}
-
Video - One way to code the solution
=====================================
diff --git a/_sources/Unit6-Arrays/horseBarnB.rst b/_sources/Unit6-Arrays/horseBarnB.rst
index ab1b80650..ebdc56797 100644
--- a/_sources/Unit6-Arrays/horseBarnB.rst
+++ b/_sources/Unit6-Arrays/horseBarnB.rst
@@ -5,18 +5,18 @@
Free Response - Horse Barn B
-------------------------------
-.. index::
- single: horse barn
+.. index::
+ single: horse barn
single: free response
-
-The following is a variation of part b of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
-The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CS A exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have.
+The following is a variation of part b of a free response question from 2012. It was question 3 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
-**Question 3.** Consider a software system that models a horse barn.
+The original question had an interface called Horse, but the problem below has been changed to a class Horse instead of the interface. Interfaces are no longer covered on the AP CSA exam. However, you can still solve problems that have interfaces in them by changing them to a class, since an interface just describes the methods that a class must have.
+**Question 3.** Consider a software system that models a horse barn.
-.. code-block:: java
+
+.. code-block:: java
public class Horse
{
@@ -27,9 +27,9 @@ The original question had an interface called Horse, but the problem below has b
/** @return the horse's weight */
public int getWeight()
{ implementation not shown }
-
+
// There may be other methods that are not shown
-
+
}
@@ -37,24 +37,27 @@ A horse barn consists of N numbered spaces. Each space can hold at most one hors
-.. code-block:: java
+.. 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) */ }
+ /**
+ * The spaces in the barn. Each array element holds a reference to the horse
+ * that is currently occupying the space. A null value indicates an empty
+ * space.
+ */
+ private Horse[] spaces;
+
+ /**
+ * Consolidates the barn by moving horses so that the horses are in adjacent
+ * spaces, starting at index 0, with no empty space between any two horses.
+ * Postcondition: The order of the horses is the same as before the
+ * consolidation.
+ */
+ public void consolidate()
+ {
+ /* to be implemented in part (b) */
+ }
}
**Part b.** Write the HorseBarn method consolidate. This method consolidates the barn by moving horses so that the horses are in adjacent spaces, starting at index 0, with no empty spaces between any two horses. After the barn is consolidated, the horses are in the same order as they were before the consolidation.
@@ -69,111 +72,202 @@ A horse barn consists of N numbered spaces. Each space can hold at most one hors
How to solve this problem
===========================
-One way to solve this problem is to create a temporary array the same size as ``spaces`` and then loop through the current ``spaces`` array and if the current element isn't null copy it to the temporary array. What kind of loop should you use? A for loop or an enhanced for loop would work for this problem. You will need an index for at least the temporary array.
+One way to solve this problem is to create a temporary array the same size as ``spaces`` and then loop through the current ``spaces`` array and if the current element isn't null copy it to the temporary array. What kind of loop should you use? A for loop or an enhanced for loop would work for this problem. You will need an index for at least the temporary array.
.. (teachers complained that you could use either because you need a 2nd index anyway) .. mchoice:: frhbb_1
- :answer_a: for
+ :answer_a: for
:answer_b: for each
:answer_c: while
:correct: a
:feedback_a: Use a for loop when you know how many times a loop needs to execute and need the index.
:feedback_b: Although you could use a for each loop, a for loop a may be the better choice because you need to use the index. Use a for each loop if you want to loop through all the elements in a collection and don't need an index.
- :feedback_c: Although you could use a for each loop, a for loop a may be the better choice because you need to use the index. Use a while loop when you don't know how many times a loop needs to execute.
+ :feedback_c: Although you could use a for each loop, a for loop a may be the better choice because you need to use the index. Use a while loop when you don't know how many times a loop needs to execute.
Which loop is a good one to use to solve this problem?
-While we are looping through the ``spaces`` array, we need to check for non-null positions.
-
-.. 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.
-
+While we are looping through the ``spaces`` array, we need to check for non-null positions. Click to reveal a practice problem about checking for null values.
+
+.. reveal:: frhbb_r2
+ :showtitle: Reveal Problem
+ :hidetitle: Hide Problem
+ :optional:
+
+ .. mchoice:: frhbb_2
+ :answer_a: if (spaces.get(index) != null)
+ :answer_b: if (!spaces[index].null())
+ :answer_c: if (spaces[index] != null)
+ :correct: c
+ :feedback_a: This is the syntax for checking an element within an ArrayList.
+ :feedback_b: Is null() a standard Java method? Comparing an object with a null value is simpler.
+ :feedback_c: "!=" is the best way to compare an element with a null value.
+
+ How do we check if the space at the current index isn't null?
+
+Try to write the code for the method ``consolidate`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution.
+
.. activecode:: lcfrhbb1
:language: java
-
- class Horse
+ :autograde: unittest
+
+ Try to write the code for the method ``consolidate`` in the ``HorseBarn`` class. When you are ready click "Run" to test your solution.
+ ~~~~
+ class Horse
{
- private String name;
- private int weight;
-
- public Horse(String theName, int theWeight)
- {
- this.name = theName;
- this.weight = theWeight;
- }
-
- public String getName() { return this.name;}
-
- public int getWeight() { return this.weight; }
-
- public String toString()
- {
- return "name: " + this.name + " weight: " + this.weight;
- }
+ private String name;
+ private int weight;
+
+ public Horse(String theName, int theWeight)
+ {
+ this.name = theName;
+ this.weight = theWeight;
+ }
+
+ public String getName()
+ {
+ return this.name;
+ }
+
+ public int getWeight()
+ {
+ return this.weight;
+ }
+
+ public String toString()
+ {
+ return "name: " + this.name + " weight: " + this.weight;
+ }
}
-
- public class HorseBarn
- {
- private Horse[] spaces;
-
- /** Constructor that takes the number of stalls
- * @param numStalls - the number of stalls in the barn
- */
- public HorseBarn(int numStalls)
- {
- spaces = new Horse[numStalls];
- }
-
-
- /** Consolidates the barn by moving horses so that the horses are
- * in adjacent spaces, starting at index 0, with no empty space
- * between any two horses.
- * Postcondition: The order of the horses is the same as before
- * the consolidation.
- */
- public void consolidate()
- {
-
- }
-
- public String toString()
- {
- String result = "";
- Horse h = null;
- for (int i = 0; i < spaces.length; i++) {
- h = spaces[i];
- result = result + "space " + i + " has ";
- if (h == null) result = result + " null \n";
- else result = result + h.toString() + "\n";
- }
- return result;
- }
-
- public static void main (String[] args)
- {
- HorseBarn barn = new HorseBarn(7);
- barn.spaces[0] = new Horse("Trigger", 1340);
- barn.spaces[2] = new Horse("Silver",1210);
- barn.spaces[5] = new Horse("Patches", 1350);
- barn.spaces[6] = new Horse("Duke", 1410);
- System.out.println("before consolidate");
- System.out.println(barn);
- barn.consolidate();
- System.out.println("after consolidate");
- System.out.println(barn);
- }
+
+ public class HorseBarn
+ {
+ private Horse[] spaces;
+
+ /**
+ * Constructor that takes the number of stalls
+ *
+ * @param numStalls - the number of stalls in the barn
+ */
+ public HorseBarn(int numStalls)
+ {
+ spaces = new Horse[numStalls];
+ }
+
+ /**
+ * Consolidates the barn by moving horses so that the horses are in adjacent
+ * spaces, starting at index 0, with no empty space between any two horses.
+ * Postcondition: The order of the horses is the same as before the
+ * consolidation.
+ */
+ public void consolidate() {}
+
+ public String toString()
+ {
+ String result = "";
+ Horse h = null;
+ for (int i = 0; i < spaces.length; i++)
+ {
+ h = spaces[i];
+ result = result + "space " + i + " has ";
+ if (h == null)
+ {
+ result = result + " null \n";
+ }
+ else
+ {
+ result = result + h.toString() + "\n";
+ }
+ }
+ return result;
+ }
+
+ public static void main(String[] args)
+ {
+ HorseBarn barn = new HorseBarn(7);
+ barn.spaces[0] = new Horse("Trigger", 1340);
+ barn.spaces[2] = new Horse("Silver", 1210);
+ barn.spaces[5] = new Horse("Patches", 1350);
+ barn.spaces[6] = new Horse("Duke", 1410);
+ System.out.println("before consolidate");
+ System.out.println(barn);
+ barn.consolidate();
+ System.out.println("after consolidate");
+ System.out.println(barn);
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.lang.reflect.Field;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "space 0 has name: Trigger weight: 1340\n"
+ + "space 1 has name: Silver weight: 1210\n"
+ + "space 2 has name: Patches weight: 1350\n"
+ + "space 3 has name: Duke weight: 1410\n"
+ + "space 4 has null \n"
+ + "space 5 has null \n"
+ + "space 6 has null";
+
+ boolean passed = removeSpaces(output).contains(removeSpaces(expect));
+ getResults(expect, output, "Expected output from main", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ HorseBarn barn = new HorseBarn(7);
+
+ try
+ {
+ Field barnField = HorseBarn.class.getDeclaredField("spaces");
+ barnField.setAccessible(true);
+
+ Horse[] spaces = (Horse[]) barnField.get(barn);
+
+ spaces[1] = new Horse("Trigger", 1340);
+ spaces[3] = new Horse("Silver", 1210);
+ spaces[5] = new Horse("Lady", 1575);
+
+ String expect =
+ "space 0 has name: Trigger weight: 1340\n"
+ + "space 1 has name: Silver weight: 1210\n"
+ + "space 2 has name: Lady weight: 1575\n"
+ + "space 3 has null \n"
+ + "space 4 has null \n"
+ + "space 5 has null \n"
+ + "space 6 has null";
+ barn.consolidate();
+ String actual = barn.toString();
+
+ boolean passed = removeSpaces(actual).contains(removeSpaces(expect));
+
+ String msg =
+ "Checking consolidate() with [null, \"Trigger\", null, \"Silver\", null,"
+ + " \"Lady\", null, null]";
+
+ getResults(expect, actual, msg, passed);
+ assertTrue(passed);
+
+ }
+ catch (Exception e)
+ {
+ getResults("", "", "There was a error with the testing code.", false);
+ fail();
+ }
+ }
}
-
Video - One way to code the solution
=====================================
diff --git a/_sources/Unit6-Arrays/numberCubeA.rst b/_sources/Unit6-Arrays/numberCubeA.rst
index 2e5f1a254..8045d5e0b 100644
--- a/_sources/Unit6-Arrays/numberCubeA.rst
+++ b/_sources/Unit6-Arrays/numberCubeA.rst
@@ -22,10 +22,13 @@ The following is a free response question from 2009. It was question 1 on the e
public class NumberCube
{
- /** @return an integer value between 1 and 6, inclusive
+ /**
+ * @return an integer value between 1 and 6, inclusive
*/
public int toss()
- { /* implementation not shown */ }
+ {
+ /* implementation not shown */
+ }
// There may be instance variables, constructors, and methods not shown.
}
@@ -36,83 +39,108 @@ method should return an array of the values produced by tossing the number cube
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?
-
+Click to reveal the algorithm and problems to help you write your solution.
+
+.. reveal:: numbercubealg_r1
+ :showtitle: Reveal Algorithm
+ :hidetitle: Hide Algorithm
+ :optional:
+
+ You will need to create an array to hold the results of each cube toss. The size of the array should be the passed number of times you will call ``toss``. You will need to loop that number of times and each time set the value of the array at that index to the result of the ``toss``. Return the array.
+
+.. reveal:: numbercubea_r1
+ :showtitle: Reveal Problems
+ :hidetitle: Hide Problems
+ :optional:
+
+ .. mchoice:: numbercubea_1
+ :answer_a: (int) (Math.random() * 6) + 1)
+ :answer_b: (int) (Math.random() * 6)
+ :answer_c: Math.random(6);
+ :correct: a
+ :feedback_a: This expression correctly generates a random number between 1 and 6.
+ :feedback_b: This expression generates a random number from 0 to 5.
+ :feedback_c: This isn't valid
+
+ Which Java expression correctly generates a random number between 1 and 6?
+
+
+ .. mchoice:: numbercubea_2
+ :answer_a: int[] tossArray = new int[];
+ :answer_b: int[] tossArray = new int(numTosses);
+ :answer_c: int[] tossArray = new int[numTosses];
+ :correct: c
+ :feedback_a: You need to specify the size of the array when you create it.
+ :feedback_b: It should be new int[numTosses].
+ :feedback_c: This will create an array of size numTosses.
+
+ Which of the following correctly creates an array of size numTosses?
+
+ .. mchoice:: numbercubea_3
+ :answer_a: for (int i = 0; i <= numTosses; i++)
+ :answer_b: for (int i = 1; i < numTosses; i++)
+ :answer_c: for (int i = 0; i < numTosses; i++)
+ :correct: c
+ :feedback_a: This will execute numTosses + 1 times.
+ :feedback_b: This will execute numTosses - 1 times.
+ :feedback_c: This will execute numTosses times.
+
+ Which of the following correctly loops numTosses number of times?
+
Mixed Up Code
-------------------
-.. parsonsprob:: NumberCubeA
- :numbered: left
- :adaptive:
-
- The method getCubeTosses below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly.
- -----
- public static int[] getCubeTosses(NumberCube cube,
- int numTosses)
- {
- =====
- int[] cubeTosses = new int[numTosses];
- =====
- for (int i = 0; i < numTosses; i++)
- {
- =====
+
+Click to reveal the Mixed Up Code for the solution to this problem.
+
+.. reveal:: numcubeA_parsons
+ :showtitle: Reveal Mixed Up Code
+ :hidetitle: Hide Mixed Up Code
+
+ .. parsonsprob:: numcubeA
+ :numbered: left
+ :adaptive:
+
+ The method ``getCubeTosses`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly.
+ -----
+ public static int[] getCubeTosses(
+ NumberCube cube,
+ int numTosses)
+ {
+ =====
+ int[] cubeTosses = new int[numTosses];
+ =====
+ for (int i = 0; i < numTosses; i++)
+ {
+ =====
cubeTosses[i] = cube.toss();
- =====
- } // end for
- =====
- return cubeTosses;
- =====
- } // end method
+ =====
+ } // 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
+ :autograde: unittest
+ FRQ Number Cube A: Write the method ``getCubeTosses`` that takes a number cube and a number of tosses as parameters. The method should return an array of the values produced by tossing the number cube the given number of times.
+ ~~~~
import java.util.Arrays;
+
public class NumberCube
{
public int toss()
{
- return (int)( (Math.random() * 6) + 1 );
+ return (int) ((Math.random() * 6) + 1);
}
public static int[] getCubeTosses(NumberCube cube, int numTosses)
@@ -120,17 +148,99 @@ Write the method ``getCubeTosses`` that takes a number cube and a number of toss
// Complete this method
}
- public static void main(String[] args) {
+ 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));
+ if (tosses.length < numTosses)
+ {
+ System.out.println(
+ "It looks like you are not returning an array of the correct"
+ + " size:");
+ System.out.println(Arrays.toString(tosses));
+ }
+ else
+ {
+ System.out.println("You returned an array of the correct size:");
+ System.out.println(Arrays.toString(tosses));
+ }
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testleng() throws IOException
+ {
+ String expect = "You returned an array of the correct size";
+ String actual = getMethodOutput("main");
+
+ boolean passed = getResults(expect, actual, "Checking output from main()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ NumberCube c = new NumberCube();
+ int[] results = NumberCube.getCubeTosses(c, 20);
+
+ String expect = "20";
+ String actual = "" + results.length;
+
+ boolean passed =
+ getResults(
+ expect,
+ actual,
+ "Checking getNumTosses() returns an array of the correct size");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ NumberCube c = new NumberCube();
+ int[] results = NumberCube.getCubeTosses(c, 100);
+
+ boolean passed = true;
+ int same = 0;
+
+ for (int i = 0; i < results.length; i++)
+ {
+ if (i < results.length - 1 && results[i] == results[i + 1]) same++;
+
+ if (results[i] < 1 || results[i] > 6) passed = false;
}
+
+ if (same > 25) passed = false;
+
+ String expect = "true";
+ String actual = "" + passed;
+
+ passed =
+ getResults(
+ expect,
+ actual,
+ "Checking that tosses are within proper range (1-6, no 0)",
+ passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ String target = "cube.toss()";
+ boolean passed = checkCodeContains("call to cube.toss()", target);
+ assertTrue(passed);
}
}
+
diff --git a/_sources/Unit6-Arrays/numberCubeB.rst b/_sources/Unit6-Arrays/numberCubeB.rst
index 9e22350da..458f1abc3 100644
--- a/_sources/Unit6-Arrays/numberCubeB.rst
+++ b/_sources/Unit6-Arrays/numberCubeB.rst
@@ -5,9 +5,9 @@
Free Response - Number Cube B
=============================
-.. index::
- single: numbercubeb
- single: free response
+.. index::
+ single: numbercubeb
+ single: free response
The following is a free response question from 2009. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
@@ -22,10 +22,13 @@ The following is a free response question from 2009. It was question 1 on the e
public class NumberCube
{
- /** @return an integer value between 1 and 6, inclusive
+ /**
+ * @return an integer value between 1 and 6, inclusive
*/
public int toss()
- { /* implementation not shown */ }
+ {
+ /* implementation not shown */
+ }
// There may be instance variables, constructors, and methods not shown.
}
@@ -34,61 +37,79 @@ The following is a free response question from 2009. It was question 1 on the e
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.
+may return either of those indices.
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.
+
+Click to reveal the algorithm for solving this problem.
+
+.. reveal:: numbercubeBalg_r1
+ :showtitle: Reveal Algorithm
+ :hidetitle: Hide Algorithm
+ :optional:
+
+ You are going to need to keep track of the current run length, the maximum run length, the index where the max run started (which should start at -1). You want to compare one value to an adjacent value
+ so you will need to be careful that you don't go out of bounds. If you find two values that are adjacent that are equal then increment the current run length and set the start index. If the two adjacent values
+ are not equal then reset the current run length to 0. Return the starting index of the maximum length run.
Mixed Up Code
-------------------
-.. parsonsprob:: NumberCubeB
- :numbered: left
- :adaptive:
- The method getLongestRun below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly.
- -----
- public static int getLongestRun(int[] values)
- {
- int currentLen = 0;
- int maxLen = 0;
- int maxStart = -1;
- =====
- for (int i = 0; i < values.length-1; i++)
- {
- =====
- if (values[i] == values[i+1])
- {
- =====
+Click to reveal the Mixed Up Code for the solution to this problem.
+
+.. reveal:: numcubeB_parsons
+ :showtitle: Reveal Mixed Up Code
+ :hidetitle: Hide Mixed Up Code
+
+ .. parsonsprob:: numcubeB
+ :numbered: left
+ :adaptive:
+
+ The method ``getLongestRun`` below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly.
+ -----
+ public static int getLongestRun(int[] values)
+ {
+ int currentLen = 0;
+ int maxLen = 0;
+ int maxStart = -1;
+ =====
+ for (int i = 0; i < values.length-1; i++)
+ {
+ =====
+ if (values[i] == values[i+1])
+ {
+ =====
currentLen++;
if (currentLen > maxLen)
{
maxLen = currentLen;
maxStart = i - currentLen + 1;
}
- =====
- } else {
+ =====
+ } else
+ {
currentLen = 0;
- }
- =====
- } // end for
- return maxStart;
- =====
- } // end method
+ }
+ =====
+ } // 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
+ :autograde: unittest
+ FRQ Number Cube B: Write the method ``getLongestRun`` that takes as its parameter an array of integer values representing a series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A run is defined as the repeated occurrence of the same value in two or more consecutive positions in the array.
+ ~~~~
public class NumberCube
{
@@ -97,19 +118,88 @@ Write the method ``getLongestRun`` that takes as its parameter an array of integ
// Complete this method
}
- public static void main(String[] args){
+ 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 != 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.");
+ 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!");
+ System.out.println(
+ "Remember that your code must return the start index of the"
+ + " longest run of tosses.");
+ }
+ else
+ {
+ System.out.println("Looks like your code works well!");
}
}
}
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void test1()
+ {
+ String expect = "Looks like your code works well!";
+ String actual = getMethodOutput("main");
+
+ boolean passed = getResults(expect, actual, "Checking output of main()");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+
+ String actual = "" + NumberCube.getLongestRun(values);
+ String expect = "-1";
+
+ boolean passed =
+ getResults(expect, actual, "Checking output with " + Arrays.toString(values));
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test3()
+ {
+ int[] values = {1, 1, 1, 1, 1, 1, 1, 1, 1};
+
+ String actual = "" + NumberCube.getLongestRun(values);
+ String expect = "0";
+
+ boolean passed =
+ getResults(expect, actual, "Checking output with " + Arrays.toString(values));
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test4()
+ {
+ int[] values = {1, 1, 1, 1, 2, 2, 2, 2, 2};
+
+ String actual = "" + NumberCube.getLongestRun(values);
+ String expect = "4";
+
+ boolean passed =
+ getResults(expect, actual, "Checking output with " + Arrays.toString(values));
+ assertTrue(passed);
+ }
+ }
+
diff --git a/_sources/Unit6-Arrays/selfDivisorB.rst b/_sources/Unit6-Arrays/selfDivisorB.rst
index d3c3ddcf3..cf22cd33a 100644
--- a/_sources/Unit6-Arrays/selfDivisorB.rst
+++ b/_sources/Unit6-Arrays/selfDivisorB.rst
@@ -5,163 +5,228 @@
Free Response - Self Divisor B
-------------------------------
-.. index::
- single: self divisor
+.. index::
+ single: self divisor
single: free response
-
-The following is part b of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
+
+The following is part b of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
**Question 1.** A positive integer is called a "self-divisor" if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self-divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors.
**Part b.** Write method firstNumSelfDivisors, which takes two positive integers as parameters, representing a start value and a number of values. Method firstNumSelfDivisors returns an array of size num that contains the first num self-divisors that are greater than or equal to start.
For example, the call firstNumSelfDivisors(10, 3) should return an array containing the values 11, 12, and 15, because the first three self-divisors that are greater than or equal to 10 are 11, 12, and 15. Be sure to use the method isSelfDivisor in your answer which we wrote in a Unit 4.10.
-.. code-block:: java
-
+.. code-block:: java
+
public class SelfDivisor
{
- /** @param number the number to be tested
- * Precondition: number > 0
- * @return true if every decimal digit of
- * number is a divisor of number;
- * false otherwise
- */
- public static boolean isSelfDivisor(int number)
- {
- int currNumber = number;
- int digit = 0;
- while (currNumber > 0)
- {
- digit = currNumber % 10;
- if (digit == 0) return false;
- if (number % digit != 0) return false;
- currNumber = currNumber / 10;
- }
- return true;
- }
-
- /**
- * @param start starting point for values to be checked
- * Precondition: start > 0
- * @param num the size of the array to be returned
- * Precondition: num > 0
- * @return an array containing the first num
- * integers >= start that are self-divisors
- */
- public static int[] firstNumSelfDivisors(int start,
- int num)
- { /* to be implemented in part (b) */ }
-
- public static void main (String[] args)
- {
- System.out.println("Self divisors for firstNumSelfDivisors(10, 3):");
- for (int n : firstNumSelfDivisors(10, 3))
- System.out.print(n + " ");
- System.out.println();
-
- System.out.println("Self divisors for firstNumSelfDivisors(22, 5)");
- for (int n : firstNumSelfDivisors(22, 5))
- System.out.print(n + " ");
- System.out.println();
- }
- }
-
+ /**
+ * @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?
-
+Click to reveal the algorithm and problems to help you write your solution.
+
+.. reveal:: selfDivBalg_r1
+ :showtitle: Reveal Algorithm
+ :hidetitle: Hide Algorithm
+ :optional:
+
+ The first thing to do is try to solve the example by hand. The question tells us to return an array of size num so we need to create an array of that size. We need
+ to loop as long as we haven't found 3 self divisors and try the current value. If the current value is a self-divisor then we add it to the array. When we have found 3 self divisors then return the array. We will need to keep track of the number of self divisors that we have found. We would try 10 (false), 11 (true so add to the array), 12 (true so add to the array), 13 (false), 14 (false), 15 (true so add to the array and return the array since we found 3).
+
+.. reveal:: frsdb_r1
+ :showtitle: Reveal Problems
+ :hidetitle: Hide Problems
+ :optional:
+
+ .. mchoice:: frsdb_1
+ :answer_a: for
+ :answer_b: for each
+ :answer_c: while
+ :correct: c
+ :feedback_a: Use a for loop when you know how many times a loop needs to execute. Do you know that here?
+ :feedback_b: Use a for each loop when you want to loop through all values in a collection. Do we have a collection here?
+ :feedback_c: Use a while loop when you don't know how many times a loop needs to execute.
+
+ Which loop should you use to solve this problem?
+
+ .. mchoice:: frsdb_2
+ :answer_a: int[] retArray = new int[3];
+ :answer_b: retArray = new int[num];
+ :answer_c: int retArray = new int[num];
+ :answer_d: int[] retArray = new int[num];
+ :answer_e: int[] retArray;
+ :correct: d
+ :feedback_a: Don't just use the size for the array from the example. The question says to return an array of size num and num could be anything.
+ :feedback_b: Don't forget to declare your variables.
+ :feedback_c: Don't forget that it is an array.
+ :feedback_d: This declares an array of ints called retArray and creates it with a size of num.
+ :feedback_e: This declares the array, but doesn't create it.
+
+ Which of the following correctly declares and creates the array to return?
+
Try to write the code for firstNumSelfDivisors. Run the main to check your answer. It should print 11, 12, and 15, and then 22, 24, 33, 36, and 44.
-
+
.. activecode:: lcfrsdb
:language: java
-
+ :autograde: unittest
+
+ FRQ SelfDivisor B: write the method firstNumSelfDivisors below.
+ ~~~~
public class SelfDivisor
{
- /** @param number the number to be tested
- * Precondition: number > 0
- * @return true if every decimal digit of
- * number is a divisor of number;
- * false otherwise
- */
- public static boolean isSelfDivisor(int number)
- {
- int currNumber = number;
- int digit = 0;
- while (currNumber > 0)
+ /**
+ * @param number the number to be tested Precondition: number > 0
+ * @return true if every decimal digit of number is a divisor of number; false
+ * otherwise
+ */
+ public static boolean isSelfDivisor(int number)
+ {
+ int currNumber = number;
+ int digit = 0;
+ while (currNumber > 0)
+ {
+ digit = currNumber % 10;
+ if (digit == 0)
+ {
+ return false;
+ }
+ if (number % digit != 0)
+ {
+ return false;
+ }
+ currNumber = currNumber / 10;
+ }
+ return true;
+ }
+
+ /**
+ * @param start starting point for values to be checked Precondition: start > 0
+ * @param num the size of the array to be returned Precondition: num > 0
+ * @return an array containing the first num integers >= start that are
+ * self-divisors
+ */
+ public static int[] firstNumSelfDivisors(int start, int num)
+ {
+ /* to be implemented in part (b) */
+ }
+
+ public static void main(String[] args)
+ {
+ System.out.println("Self divisors for firstNumSelfDivisors(10, 3):");
+ for (int n : firstNumSelfDivisors(10, 3))
+ {
+ System.out.print(n + " ");
+ }
+ System.out.println();
+
+ System.out.println("Self divisors for firstNumSelfDivisors(22, 5):");
+ for (int n : firstNumSelfDivisors(22, 5))
+ {
+ System.out.print(n + " ");
+ }
+ System.out.println();
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "Self divisors for firstNumSelfDivisors(10, 3):\n"
+ + "11 12 15\n"
+ + "Self divisors for firstNumSelfDivisors(22, 5):\n"
+ + "22 24 33 36 44";
+ boolean passed = getResults(expect, output, "Checking output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
{
- digit = currNumber % 10;
- if (digit == 0) return false;
- if (number % digit != 0) return false;
- currNumber = currNumber / 10;
+ String msg = "Checking firstNumSelfDivisors(5, 10)";
+ String output = Arrays.toString(SelfDivisor.firstNumSelfDivisors(5, 10));
+ String expect = "[5, 6, 7, 8, 9, 11, 12, 15, 22, 24]";
+
+ boolean passed = getResults(expect, output, msg);
+ assertTrue(passed);
}
- 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.
+There are many possible solutions to this problem. The video below (at https://www.youtube.com/watch?v=2VBz-pX1Xos ) shows one solution.
+
+.. youtube:: 2VBz-pX1Xos
+ :width: 800
+ :align: center
+
-.. 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/Unit6-Arrays/soundA.rst b/_sources/Unit6-Arrays/soundA.rst
index 6a15fea3d..f55d7e745 100644
--- a/_sources/Unit6-Arrays/soundA.rst
+++ b/_sources/Unit6-Arrays/soundA.rst
@@ -22,12 +22,12 @@ A partial declaration of the ``Sound`` class is shown below.
/** 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
+ /** 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
+ * @return the number of values in this sound that this
* method changed
*/
public int limitAmplitude(int limit)
@@ -36,13 +36,13 @@ A partial declaration of the ``Sound`` class is shown below.
/** 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
+ * 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
+ // There may be instance variables, constructors, and methods
// that are not shown.
}
@@ -76,109 +76,209 @@ is executed, the value of ``numChanges`` will be 5, and the array ``samples`` wi
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.
+Click to reveal problems and the algorithm to help you write your solution.
-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.
+.. reveal:: soundA_algorithm_r1
+ :showtitle: Reveal Algorithm
+ :hidetitle: Hide Algorithm
+ :optional:
-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 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.
-We will have to return the count 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.
-.. 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.
+ 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.
- 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.
+ We will have to return the count of values changed.
- Which is the correct code for changing the current value to the negative of the limit?
+.. reveal:: fr_sounda_r1
+ :showtitle: Reveal Problems
+ :hidetitle: Hide Problems
+ :optional:
+
+ .. mchoice:: fr_sounda_1
+ :answer_a: while
+ :answer_b: for
+ :answer_c: for-each
+ :correct: b
+ :feedback_a: You could use a while loop, but if you are looping through all values in an array it is better to use a for loop. It is easier to make mistakes with a while loop and forget to increment a value in the body of the loop so that the loop eventually stops.
+ :feedback_b: Use a for loop when you want to loop through all or part of an array and need to change some of the values in the array.
+ :feedback_c: You could use a for-each loop to loop through all of the values in the array, but you wouldn't be able to change the values.
+
+ Which loop would be best for this problem?
+
+ .. mchoice:: fr_sounda_2
+ :answer_a: samples[i].set(-limit);
+ :answer_b: samples[i] = limit;
+ :answer_c: samples[i] = -limit;
+ :correct: c
+ :feedback_a: There is no set method on arrays.
+ :feedback_b: This would set the value at index i to limit rather than the negative of the limit.
+ :feedback_c: This will set the value at index i to the negative of the limit.
+
+ Which is the correct code for changing the current value to the negative of the limit?
Mixed Up Code
-------------------
-.. parsonsprob:: SoundA
- :numbered: left
- :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)
+Click to reveal the Mixed Up Code for the solution of this problem.
+
+.. reveal:: soundA_parsons
+ :showtitle: Reveal Mixed Up Code
+ :hidetitle: Hide Mixed Up Code
+
+ .. parsonsprob:: SoundA
+ :numbered: left
+ :adaptive:
+ :noindent:
+
+ The method ``limitAmplitude`` below contains the correct code for a solution to this problem, but the code blocks are mixed up. Drag the blocks from the left to the right and put them in order with the correct indentation so that the code would work correctly.
+ -----
+ public int limitAmplitude(int limit)
+ {
+ =====
+ int numChanged = 0;
+ for (int i = 0; i < samples.length; i++)
+ {
+ =====
+ if (samples[i] > limit)
{
- =====
- samples[i] = limit;
- numChanged++;
- =====
+ =====
+ samples[i] = limit;
+ numChanged++;
+ =====
} // end first if
- if (samples[i] < -limit)
+ if (samples[i] < -limit)
{
- =====
- samples[i] = -limit;
- numChanged++;
- =====
- } // end second if
- =====
- } // end for
- =====
- return numChanged;
- =====
- } // end method
+ =====
+ 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
+ :autograde: unittest
+ FRQ Sound A: Write the method ``limitAmplitude`` that will change any value that has an amplitude greater than the given limit. Values that are greater than ``limit`` are replaced with ``limit``, and values that are less than ``-limit`` are replaced with ``–limit``. The method returns the total number of values that were changed in the array. The ``main`` method has code to test your solution.
+ ~~~~
import java.util.Arrays;
+
public class Sound
{
// the array of values in this sound; guaranteed not to be null
- private int[] samples = { 40, 2532, 17, -2300, -17, -4000, 2000, 1048, -420, 33, 15, -32, 2030, 3223};
-
- /** Changes those values in this sound that have an amplitude greater than limit
- * Values greater than limit are changed to limit.
- * @param limit the amplitude limit
- * Precondition: limit >= 0
- * @return the number of values in this sound that this method changed
+ 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 int limitAmplitude(int limit)
+ {
+ // Complete this method
}
- public static void main(String[] args){
-
+ 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(
+ "limitAmplitude(2000) should return 5 "
+ + "and returned "
+ + s.limitAmplitude(2000));
System.out.println("The changed array is: " + Arrays.toString(s.samples));
-
}
}
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.lang.reflect.Field;
+ import java.util.Arrays;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+ String expect =
+ "40, 2000, 17, -2000, -17, -2000, 2000, 1048, -420, 33, 15, -32, 2000, 2000";
+ boolean passed = output.contains(expect);
+
+ expect =
+ "The original array is: [40, 2532, 17, -2300, -17, -4000, 2000, 1048, -420, 33, 1\n"
+ + "5, -32, 2030, 3223]\n"
+ + "limitAmplitude(2000) should return 5 and returned 5\n"
+ + "The changed array is: [40, 2000, 17, -2000, -17, -2000, 2000, 1048, -420,"
+ + " 33, 15, -32, 2000, 2000]";
+
+ getResults(expect, output, "Checking output from main()", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test1()
+ {
+ Sound s = new Sound();
+
+ String expected = "8";
+ String actual = "" + s.limitAmplitude(75);
+
+ String msg = "Checking limitAmplitude(75) return value";
+ boolean passed = getResults(expected, actual, msg);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ Sound s = new Sound();
+ s.limitAmplitude(75);
+
+ try
+ {
+ Field sampleField = Sound.class.getDeclaredField("samples");
+ sampleField.setAccessible(true);
+
+ int[] samples = (int[]) sampleField.get(s);
+
+ String expected = "[40, 75, 17, -75, -17, -75, 75, 75, -75, 33, 15, -32, 75, 75]";
+ String actual = Arrays.toString(samples);
+
+ String msg = "Checking limitAmplitude(75) array results";
+ boolean passed = getResults(expected, actual, msg);
+ assertTrue(passed);
+
+ }
+ catch (Exception e)
+ {
+ getResults("", "", "There was a error with the testing code.", false);
+ fail();
+ }
+ }
+ }
+
diff --git a/_sources/Unit6-Arrays/soundB.rst b/_sources/Unit6-Arrays/soundB.rst
index 5d0f42550..bf3658d72 100644
--- a/_sources/Unit6-Arrays/soundB.rst
+++ b/_sources/Unit6-Arrays/soundB.rst
@@ -5,8 +5,8 @@
Free Response - Sound B
=======================
-.. index::
- single: soundb
+.. index::
+ single: soundb
single: free response
The following is a free response question from 2011. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.
@@ -22,12 +22,12 @@ A partial declaration of the ``Sound`` class is shown below.
/** 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
+ /** 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
+ * @return the number of values in this sound that this
* method changed
*/
public int limitAmplitude(int limit)
@@ -36,13 +36,13 @@ A partial declaration of the ``Sound`` class is shown below.
/** 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
+ * 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
+ // There may be instance variables, constructors, and methods
// that are not shown.
}
@@ -69,99 +69,184 @@ After ``trimSilenceFromBeginning`` has been called, the instance variable ``samp
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``?
+
+Click to reveal problems and the algorithm to help you write your solution.
+
+.. reveal:: soundB_algorithm_r1
+ :showtitle: Reveal Algorithm
+ :hidetitle: Hide Algorithm
+ :optional:
+
+ 1. You will need to loop through each element in the array until you reach a non-zero element. You will also need to keep track of the number of leading zeros.
+ 2. Remember that you must replace the samples array with a new array without the leading zeros. How do you create an array of a particular size?
+
+
+.. reveal:: fr_soundb_r1
+ :showtitle: Reveal Problems
+ :hidetitle: Hide Problems
+ :optional:
+
+ .. mchoice:: fr_soundb_1
+ :answer_a: while
+ :answer_b: for
+ :answer_c: for-each
+ :correct: a
+ :feedback_a: A while loop is the best choice when you don't know the number of times you need to loop.
+ :feedback_b: You could use a for loop, but typically a while loop is used when you want to loop while a condition is true.
+ :feedback_c: A for-each loop would only allow you to loop through all the values, but you first want to loop while there are leading zeros.
+
+ Which loop would be best for this problem?
+
+ .. mchoice:: fr_soundb_2
+ :answer_a: int[] samples2;
+ :answer_b: int[] samples2 = new Array(count);
+ :answer_c: int[] samples2 = new int[count];
+ :correct: c
+ :feedback_a: This only declares the variable samples2 which will refer to an array of integers, it doesn't create the array object.
+ :feedback_b: The new keyword is not used to create an array.
+ :feedback_c: This will create an array of integers of size count and a variable named samples2 which will refer to that array.
+
+ Which is the correct code for creating an integer array variable named ``samples2`` and setting it to refer to an array of integers of size ``count``?
Mixed Up Code
-------------------
-.. parsonsprob:: SoundB
- :numbered: left
- :adaptive:
-
- The method trimSilenceFromBeginning below contains correct code for one solution to this problem, but it is mixed up. Drag the code blocks from the left to the right and put them in order with the correct indention so that the code would work correctly.
- -----
- public void trimSilenceFromBeginning()
- {
- int i = 0;
- =====
- while (this.samples[i] == 0)
- {
- =====
+Click to reveal the Mixed Up Code for the solution of this problem.
+
+.. reveal:: soundB_parsons
+ :showtitle: Reveal Mixed Up Code
+ :hidetitle: Hide Mixed Up Code
+
+ .. parsonsprob:: SoundB
+ :numbered: left
+ :adaptive:
+
+ The method ``trimSilenceFromBeginning`` below contains correct code for one solution to this problem, but it is mixed up. Drag the code blocks from the left to the right and put them in order with the correct indention so that the code would work correctly.
+ -----
+ public void trimSilenceFromBeginning()
+ {
+ int i = 0;
+ =====
+ while (this.samples[i] == 0)
+ {
+ =====
i++;
- =====
- } // end while
- =====
- int samplesLen = this.samples.length;
- int[] newSamples = new int[samplesLen - i];
- =====
- for (int j = 0; j < newSamples.length; j++)
- {
- =====
+ =====
+ } // 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
+ =====
+ } // 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
+ :autograde: unittest
+ FRQ Sound B: Finish writing the method ``trimSilenceFromBeginning`` below that removes the silence from the beginning of a sound. To remove starting silence, a new array of values is created that contains the same values as the original ``samples`` array in the same order but without the leading zeros. The instance variable ``samples`` is updated to refer to the new array.
+ ~~~~
import java.util.Arrays;
+
public class Sound
{
/** the array of values in this sound; guaranteed not to be null */
- private int[] samples = {0, 0, 0, 0, -14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0};
-
- /** Removes all silence from the beginning of this sound.
- * Silence is represented by a value of 0.
- * Precondition: samples contains at least one nonzero value
- * Postcondition: the length of samples reflects the removal of starting silence
+ 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
+ // 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);
+
+ Sound s = new Sound();
+
+ System.out.println(
+ "The original array of samples is " + Arrays.toString(s.samples));
+ s.trimSilenceFromBeginning();
+ System.out.println(
+ "The new array of samples is " + Arrays.toString(s.samples));
+ System.out.println(
+ "The length of the new array should be 12 and is "
+ + s.samples.length);
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+
+ import org.junit.*;
+
+ import java.io.*;
+ import java.lang.reflect.Field;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testMain()
+ {
+ String output = getMethodOutput("main");
+ String expect = "-14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0";
+
+ boolean passed = output.contains(expect);
+
+ expect =
+ "The original array of samples is [0, 0, 0, 0, -14, 0, -35, -39, 0, -7, 16, 32, 37,"
+ + " 29, 0, 0]\n"
+ + "The new array of samples is [-14, 0, -35, -39, 0, -7, 16, 32, 37, 29, 0, 0]";
+
+ getResults(expect, output, "Checking output from main()", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2()
+ {
+ Sound s = new Sound();
+ s.trimSilenceFromBeginning();
+
+ try
+ {
+ Field sampleField = Sound.class.getDeclaredField("samples");
+ sampleField.setAccessible(true);
+
+ int[] samples = (int[]) sampleField.get(s);
+
+ String expected = "12";
+ String actual = "" + samples.length;
+
+ String msg = "Checking samples array length after trimSilenceFromBeginning()";
+ boolean passed = getResults(expected, actual, msg);
+ assertTrue(passed);
+
+ }
+ catch (Exception e)
+ {
+ getResults("", "", "There was a error with the testing code.", false);
+ fail();
+ }
}
}
+
diff --git a/_sources/Unit6-Arrays/toctree.rst b/_sources/Unit6-Arrays/toctree.rst
index ac3d83390..ee43d4f44 100644
--- a/_sources/Unit6-Arrays/toctree.rst
+++ b/_sources/Unit6-Arrays/toctree.rst
@@ -7,7 +7,7 @@ Arrays
Class Periods: 6-8
-AP CS A Exam Weighting: 10-15%
+AP CSA Exam Weighting: 10-15%
.. toctree::
:maxdepth: 3
@@ -18,6 +18,8 @@ AP CS A Exam Weighting: 10-15%
topic-6-4-array-algorithms.rst
topic-6-5-summary.rst
ArrayParsonsPractice.rst
+ Arrays-mixed-code-toggle.rst
ArrayPractice.rst
Exercises.rst
- arrayExam.rst
\ No newline at end of file
+ arrayExam.rst
+ MoreArrayPractice.rst
diff --git a/_sources/Unit6-Arrays/topic-6-1-array-basics.rst b/_sources/Unit6-Arrays/topic-6-1-array-basics.rst
index 4cf3e9e79..c5373658b 100644
--- a/_sources/Unit6-Arrays/topic-6-1-array-basics.rst
+++ b/_sources/Unit6-Arrays/topic-6-1-array-basics.rst
@@ -1,49 +1,36 @@
+.. include:: ../common.rst
+
.. qnum::
:prefix: 6-1-
:start: 1
-.. |CodingEx| image:: ../../_static/codingExercise.png
- :width: 30px
- :align: middle
- :alt: coding exercise
-
-
-.. |Exercise| image:: ../../_static/exercise.png
- :width: 35
- :align: middle
- :alt: exercise
-
-
-.. |Groupwork| image:: ../../_static/groupwork.png
- :width: 35
- :align: middle
- :alt: groupwork
-
+|Time90|
Array Creation and Access
---------------------------
+==========================
-.. index::
- single: array
- single: index
- pair: array; index
+.. index::
+ single: array
+ single: index
+ pair: array; index
-To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, … , score10;
-But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple **data structure** for a collection of related data that makes this easier. In App Inventor, this is called a list. In Java and many programming languages, this is called an **array**.
+To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, … , score10;
+But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple **data structure** for a collection of related data that makes this easier. In many block-based programming languages like App Inventor and Scratch, this is called a list. In Java and many programming languages, this is called an **array**.
-An **array** is a block of memory that stores a collection of data items (**elements**) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don't need to name each one. Instead you use the array name and a number (called an **index**) for the position of an item in the array. You can make arrays of ints, doubles, Strings, and even classes that you have written like Students.
+An **array** is a block of memory that stores a collection of data items (**elements**) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don't need to name each one. Instead you use the array name and a number (called an **index**) for the position of an item in the array. You can make arrays of ints, doubles, Strings, and even classes that you have written like Students.
.. |video| raw:: html
video
-
+
Here's a fun |video| that introduces the concept of an array and gives an example.
.. youtube:: G7aF-OuLfl4
:width: 640
+ :height: 415
:align: center
-An array is like a row of small lockers, except that you can't cram lots of stuff into it. You can only store one value at each locker.
+An array is like a row of small lockers, except that you can't cram lots of stuff into it. You can only store one value at each locker.
.. figure:: Figures/rowLockers.jpg
@@ -53,7 +40,7 @@ An array is like a row of small lockers, except that you can't cram lots of stuf
Figure 1: A row of lockers
-You can store a value in an array using an **index** (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index.
+You can store a value in an array using an **index** (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index.
Arrays and lists in most programming languages start counting elements from the number 0, so the first element in an array is at index 0. This is similar to how Strings are indexed in Java -- the first character is at index 0. If you used App Inventor in the past, you might remember that list elements there start at 1 instead of 0, so make sure you remember that in Java, arrays start the index at 0!
@@ -61,42 +48,56 @@ Arrays and lists in most programming languages start counting elements from the
:width: 100%
:align: center
:figclass: align-center
-
+
Figure 2: Comparing App Inventor lists and Java arrays
-
+
.. shortanswer:: arrayAnalogy
Can you think of another example of something that is like an array (like a row of lockers)?
-
+
Declaring and Creating an Array
-===============================
+-------------------------------
+
+When we declare a variable, we specify its type and then the variable name. To make a variable into an array, we put square brackets after the data type. For example, ``int[] scores`` means we have an array called scores that contains int values.
-When we declare a variable, we specify its type and then the variable name. To make a variable into an array, we put square brackets after the data type. This data type will be for all the elements in the array.
+.. code-block:: java
-.. code-block:: java
-
- // Declaration for a single int variable
+ // Declaration for a single int variable
int score;
// Declaration for an array of ints
int[] scores;
-The declarations do not create the array. Arrays are **objects** in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet).
+The declarations do not create the array. Arrays are **objects** in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print **null** (meaning it doesn't reference any object yet).
+There are two ways to create an array. You can use the keyword **new** to get new memory or use an **initializer list** to set up the values in the array.
+.. |video2| raw:: html
-To actually create an array after declaring the variable, use the **new** keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. You can do the declaration and the creation all in one step, see the String array names below. The size of an array is set at the time of creation and cannot be changed after that.
+ video
+
+Watch the following |video2| which shows the two ways of creating an array with a physical model of Java memory.
+
+.. youtube:: IbPFjw1FNkE
+ :width: 650
+ :height: 415
+ :align: center
+
+Using new to Create Arrays
+--------------------------
+
+To create an empty array after declaring the variable, use the **new** keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. You can do the declaration and the creation all in one step, see the String array names below. The size of an array is set at the time of creation and cannot be changed after that.
+
+.. code-block:: java
-.. code-block:: java
-
//declare an array variable
int[] highScores;
// create the array
highScores = new int[5];
// declare and create array in 1 step!
String[] names = new String[5];
-
+
|Exercise| **Check Your Understanding**
@@ -112,7 +113,7 @@ To actually create an array after declaring the variable, use the **new** keywor
:feedback_b: Yes correct!
:feedback_c: This declares the array but does not create it with new.
:feedback_d: This is not the correct syntax.
-
+
Which of the following creates an array of 10 doubles called prices?
|CodingEx| **Coding Exercise**
@@ -124,62 +125,67 @@ To actually create an array after declaring the variable, use the **new** keywor
:language: java
:autograde: unittest
:practice: T
-
- In the following code, add another array declaration that creates an array of 5 doubles called prices and another array of 5 Strings called names and corresponding System.out.println commands.
+
+ In the following code, add another two more array declarations, one that creates an array of 5 doubles called prices and another of 5 Strings called names. Then add ``System.out.println`` calls to print their lengths.
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- // Array example
- int[] highScores = new int[10];
- // Add an array of 5 doubles called prices.
-
- // Add an array of 5 Strings called names.
-
- System.out.println("Array highScores declared with size " + highScores.length);
- // Print out the length of the new arrays
- }
+ public static void main(String[] args)
+ {
+ // Array example
+ int[] highScores = new int[10];
+ // Add an array of 5 doubles called prices.
+
+ // Add an array of 5 Strings called names.
+
+ System.out.println(
+ "Array highScores declared with size " + highScores.length);
+ // Print out the length of the new arrays
+ }
}
+
====
import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("Test1");
- }
+ import org.junit.*;
- @Test
- public void testDouble() throws IOException
- {
- String target = "new double[5];";
- boolean passed = checkCodeContains(target);
- assertTrue(passed);
- }
+ import java.io.*;
- @Test
- public void testString() throws IOException
- {
- String target = "new String[5];";
- boolean passed = checkCodeContains(target);
- assertTrue(passed);
- }
- }
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Test1");
+ }
+
+ @Test
+ public void testDouble() throws IOException
+ {
+ String target = "new double[5];";
+ boolean passed = checkCodeContains(target);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testString() throws IOException
+ {
+ String target = "new String[5];";
+ boolean passed = checkCodeContains(target);
+ assertTrue(passed);
+ }
+ }
+
+.. index::
+ pair: array; initialization
-.. index::
- pair: array; initialization
-
.. note::
-
- Array elements are initialized to default values like the following.
-
- - 0 for elements of type ``int``
- - 0.0 for elements of type ``double``
+
+ Array elements are initialized to default values like the following.
+
+ - 0 for elements of type ``int``
+ - 0.0 for elements of type ``double``
- false for elements of type ``boolean``
- - null for elements of type ``String``
+ - null for elements of type ``String``
.. figure:: Figures/arrayIndicies.png
:width: 200px
@@ -188,20 +194,18 @@ To actually create an array after declaring the variable, use the **new** keywor
Figure 3: Two 5 element arrays with their values set to the default values for integer and object arrays.
-Initializer Lists
-============================
+Initializer Lists to Create Arrays
+------------------------------------
-Another way to create an array is to use an **initializer list**. You can initialize (set) the values in the array to a list of values in curly brackets { } when you create it, like below. In this case you don't specify the size of the array, it will be determined from the number of values that you specify.
+Another way to create an array is to use an **initializer list**. You can initialize (set) the values in the array to a list of values in curly braces (``{}``) when you create it, like below. In this case you don't specify the size of the array, it will be determined from the number of values that you specify.
-.. code-block:: java
+.. 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.
+
+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
@@ -210,11 +214,23 @@ When you create an array of a **primitive type** (like ``int``) with initial val
Figure 4: A primitive array and an object array
-.. index::
- single: dot-notation
- pair: array; length
+.. |video3| raw:: html
+ video
+Watch the following |video3| which shows an array of String objects with a physical model of Java memory.
+
+.. youtube:: T-YZvVvPOac
+ :width: 650
+ :height: 415
+ :align: center
+
+.. index::
+ single: dot-notation
+ pair: array; length
+
+Array length
+--------------------------
Arrays know their length (how many elements they can store). It is a public read-only instance variable so you can use **dot-notation** to access the instance variable (``arrayName.length``). **Dot-notation** is using variable name followed by a ``.`` and then the instance variable (property) name or a method name. Try the following.
@@ -224,75 +240,80 @@ Arrays know their length (how many elements they can store). It is a public rea
.. activecode:: lcab2
:language: java
- :autograde: unittest
-
+ :autograde: unittest
+
Try running the code below to see the length. Try adding another value to the highScores initializer list and run again to see the length value change.
~~~~
public class Test2
{
- public static void main(String[] args)
- {
- int[ ] highScores = {99,98,98,88,68};
- System.out.println(highScores.length);
- }
+ public static void main(String[] args)
+ {
+ int[] highScores = {99, 98, 98, 88, 68};
+ System.out.println(highScores.length);
+ }
}
+
====
// Test for Lesson 6.1.2 - While Loop FindAndReplace lclw1
- import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("Test2");
- }
-
- @Test
- public void testMain() throws IOException
- {
- String output = getMethodOutput("main").trim();
- String expect = "6";
-
- //boolean pass = !output.equals(expect.trim());
-
- boolean passed = getResults(expect, output, "Did you add another value?");
- assertTrue(passed);
- }
-
- @Test
- public void testChangedCode() {
- String origCode = "public class Test2 { public static void main (String [] args) { int [] highScores = {99,98,98,88,68}; System.out.println(highScores.length); } }";
+ import static org.junit.Assert.*;
- boolean changed = codeChanged(origCode);
+ import org.junit.*;
- assertTrue(changed);
-
- }
- }
+ import java.io.*;
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Test2");
+ }
+
+ @Test
+ public void testMain() throws IOException
+ {
+ String output = getMethodOutput("main").trim();
+ String expect = "6";
+
+ // boolean pass = !output.equals(expect.trim());
+
+ boolean passed = getResults(expect, output, "Did you add another value?");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void testChangedCode()
+ {
+ String origCode =
+ "public class Test2 { public static void main (String [] args) { int [] highScores"
+ + " = {99,98,98,88,68}; System.out.println(highScores.length); } }";
+
+ boolean changed = codeChanged(origCode);
+
+ assertTrue(changed);
+ }
+ }
.. note::
Note that length is an instance variable and not a method, unlike the String ``length()`` method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. The length instance variable is declared as a ``public final int``. ``public`` means you can access it and ``final`` means the value can't change.
-
+
|Exercise| **Check your understanding**
-
+
.. mchoice:: qab_2
:practice: T
:answer_a: highScores.length
:answer_b: highScores.length - 1
:correct: b
- :feedback_a: Remember that the first element in an array starts at index 0. If the length (the number of elements) of the array is 5, at what index would you find the last element?
+ :feedback_a: Remember that the first element in an array starts at index 0. If the length (the number of elements) of the array is 5, at what index would you find the last element?
:feedback_b: Since the first element in an array is at index 0 the last element is the length minus 1.
Which index is for the last element of an array called ``highScores``?
-
-Access and Modify Array Values
-=====================================
+
+Access and Modify Array Values
+-------------------------------------
To access the items in an array, we use an **indexed array variable** which is the array name and the index inside of square bracket [ ]. Remember that an **index** is a number that indicates the position of an item in a list, starting at 0. Here's a comparison of App Inventor, AP CSP Pseudocode, and Java array access.
@@ -301,122 +322,65 @@ To access the items in an array, we use an **indexed array variable** which is t
:width: 100%
:align: center
:figclass: align-center
-
+
Figure 5: Comparing Access to App Inventor lists and Java arrays
An indexed variable like **arrayname[index]** can be used anywhere a regular variable can be used, for example to assign a new value or to get a value from the array like below.
-.. code-block:: java
-
+.. code-block:: java
+
// assign a new value 99 to the first element in the array
highScores[0] = 99;
// print the first element of the array
System.out.println( highScores[0] );
-
+
.. note::
The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). Use arrayname[index] to access or modify array items.
-
+.. |video4| raw:: html
+
+ video
+
+Watch the following |video4| which shows a physical model of Java memory setting array values.
+
+.. youtube:: uagEJw6bTM4
+ :width: 650
+ :height: 415
+ :align: center
|Exercise| **Check your understanding**
.. fillintheblank:: array-access1
-
- Fill in the blank with code to access the cars array.
-
+ Fill in the blank with code to access the cars array. NOTE: The semicolon is provided for you after the box.
+
+
String[] cars = {"Honda", "Volvo", "BMW"};
-
+
// Access cars array to get Volvo
-
+
String v = |blank|;
- :cars\[1\]: Correct.
- :x: Use the array name cars with [ ] with a number in it. Don't use spaces in your answer!
-
+ :x: Use the array name cars with [ ] with a number in it. Don't use spaces or ; in your answer!
+
.. fillintheblank:: array-access2
- Fill in the blank with code to access the cars array. NOTE: The semicolon is provided for you after the box.
-
+ Fill in the blank with code to access the cars array.
+
String[] cars = {"Honda", "Volvo", "BMW"};
-
+
// Set the first item of the cars array to be Toyota
-
- |blank| = "Toyota";
+
+ |blank| = "Toyota";
- :cars\[0\]: Correct.
:x: Use the array name cars with [ ] with a number in it. Remember which index is for the first item in the array. Don't use spaces in your answer!
-.. .. 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
- :practice: T
- :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.
-
- At what index do you find the first element of an array?
-
-.. .. 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 |
- +----+----+----+----+
-
-
-.. **Coding Exercise**
-
-.. Try out the following code which has an int array of highScores and names. Can you print out 3rd score in the array (remember that the first score is at index 0)? Can you change last score to 97 using an assignment statement in the code? Can you change the array so that it has 6 elements and add another score and print it out? What happens if you try to access an element that is not there, for example at index 7?
-
-.. .. activecode:: arrayAccess
- :language: java
-
- public class Test1
- {
- public static void main(String[] args)
- {
- // declare and create arrays
- int[ ] highScores = new int[5];
- // Print initial highScore
- System.out.println(scores[0]);
- // put values in highScore using an indexed variable
- highScores[0] = 99;
- highScores[1] = 98;
- highScores[2] = 98;
- highScores[3] = 88;
- highScores[4] = 68;
-
- // Print first highScore at index 0
- System.out.println( highScores[0] );
-
- }
- }
-
-
-
-
-
-
-If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two **parallel arrays**. One array could keep track of the scores and the other the names. You have to make sure you keep them in the same order so that the same index can be used to get correponding names and scores.
+If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two **parallel arrays**. One array could keep track of the scores and the other the names. You have to make sure you keep them in the same order so that the same index can be used to get correponding names and scores.
|CodingEx| **Coding Exercise**
@@ -424,72 +388,76 @@ If you want to keep track of the top 5 highest scores in a game and the names of
.. activecode:: array-set
:language: java
- :autograde: unittest
-
- Try out the following code which has two parallel arrays, highScores and names. Can you print out Mateo's score? Can you change Sofia's score to 97 using an assignment statement in the code? Can you change the arrays so that they have 6 elements and add your name and score and print them out?
+ :autograde: unittest
+
+ Try out the following code which has two parallel arrays, highScores and names. Can you print out Mateo's score? Can you change Sofia's score to 97 using an assignment statement in the code? Can you change the arrays so that they have 6 elements and add your name and score and print them out?
~~~~
public class Test1
{
- public static void main(String[] args)
- {
- // declare, create, initialize arrays
- int[ ] highScores = {99,98,98,88,68};
- String[ ] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};
-
- // Print corresponding names and scores
- System.out.println(names[0] + " has a score of " + highScores[0]);
- System.out.println(names[1] + " has a score of " + highScores[1]);
- }
+ public static void main(String[] args)
+ {
+ // declare, create, initialize arrays
+ int[] highScores = {99, 98, 98, 88, 68};
+ String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};
+
+ // Print corresponding names and scores
+ System.out.println(names[0] + " has a score of " + highScores[0]);
+ System.out.println(names[1] + " has a score of " + highScores[1]);
+ }
}
+
====
// Test for Lesson 6.1.2 - While Loop FindAndReplace lclw1
- import static org.junit.Assert.*;
- import org.junit.*;;
- import java.io.*;
-
- public class RunestoneTests extends CodeTestHelper
- {
- public RunestoneTests() {
- super("Test1");
- }
+ import static org.junit.Assert.*;
- @Test
- public void test1() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Jamal has a score of 99\nEmily has a score of 98";
+ import org.junit.*;
- boolean passed = !output.equals(expect);
+ import java.io.*;
- passed = getResults(expect, output, "Did you change the main?", passed);
- assertTrue(passed);
- }
+ public class RunestoneTests extends CodeTestHelper
+ {
+ public RunestoneTests()
+ {
+ super("Test1");
+ }
+
+ @Test
+ public void test1() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Jamal has a score of 99\nEmily has a score of 98";
+
+ boolean passed = !output.equals(expect);
+
+ passed = getResults(expect, output, "Did you change the main?", passed);
+ assertTrue(passed);
+ }
+
+ @Test
+ public void test2() throws IOException
+ {
+ String output = getMethodOutput("main");
+ String expect = "Mateo has a score of 88";
+
+ boolean passed = output.contains("Mateo");
+
+ passed = getResults(expect, output, "Did you print out Mateo?", passed);
+ assertTrue(passed);
+ }
+ }
- @Test
- public void test2() throws IOException
- {
- String output = getMethodOutput("main");
- String expect = "Mateo has a score of 88";
+What happens if you try to access an element that is not there? Try to access a ``highScore`` or ``name`` at index 7 above to see what happens. The index must be between 0 and the length of the array - 1 or it will give an error message called ``ArrayIndexOutOfBoundsException``.
- boolean passed = output.contains("Mateo");
+.. note::
- passed = getResults(expect, output, "Did you print out Mateo?", passed);
- assertTrue(passed);
- }
- }
-
-What happens if you try to access an element that is not there? Try to access a highScore or name at index 7 above to see what happens. The index must be between 0 and the length of the array - 1 or it will give an error message called ArrayIndexOutOfBoundsException.
+ Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown.
-.. note::
- Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown.
-
+One powerful feature in the array **data abstraction** is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index.
-One powerful feature in the array **data abstraction** is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index.
+.. code-block:: java
-.. code-block:: java
-
// use a variable for the index
int index = 3;
System.out.println( highScores[index] );
@@ -497,179 +465,419 @@ One powerful feature in the array **data abstraction** is that we can use variab
.. image:: 6-1-images/cow.jpg
:width: 150
:align: left
-
+
|CodingEx| **Coding Exercise**
-Here's a fun String array of image filenames. The following code displays an online image using an HTML tag. (Note that this just works in this Active Code window which interprets HTML. In other Java IDEs you would need to use Java Swing graphics instead). Run the code and see that it displays images[0] which is "cow.jpg". The images array holds 5 images.
+Here's a fun String array of image filenames. The following code displays an online image using an HTML tag. (Note that this just works in this Active Code window which interprets HTML. In other Java IDEs you would need to use Java Swing graphics instead). Run the code and see that it displays images[0] which is "cow.jpg". The images array holds 5 images.
+
-
.. activecode:: imageArray
:language: java
-
+ :autograde: unittest
+
Can you change the index variable's value so that it prints out the puppy image? Can you print out the reindeer? Try all of them! What indices did you need to use? Then try using a random number for the index instead. Remember that (int)(Math.random()*max) will return a number from 0 up to max. What's the maximum number it can be for this array?
~~~~
public class ImageEx
- {
- public static void main(String[] args)
+ {
+ public static void main(String[] args)
+ {
+ String[] images =
+ {
+ "cow.jpg", "kitten.jpg", "puppy.jpg", "pig.jpg", "reindeer.jpg"
+ };
+
+ ImageEx obj = new ImageEx();
+ // Change index to see different images in the array!
+ // Can you have it pick out a random image?
+ int index = 0;
+ obj.printHTMLimage(images[index]);
+ }
+
+ // This method will just work in Active Code which interprets html
+ public void printHTMLimage(String filename)
+ {
+ String baseURL =
+ "https://raw.githubusercontent.com/bhoffman0/CSAwesome/master/_sources/Unit6-Arrays/6-1-images/";
+ System.out.print("Precondition: loc is valid in this grid
+ *
+ * @param loc a location in this grid
+ * @return returns an array list of the objects in the occupied locations
+ * adjacent to loc in this grid
+ */
+ ArrayList", "
");
String[] tokens2 = {"", "yy", "
", "zz", ""};
- ArrayList,
, ] and it prints" + res2);
+ ArrayList,
, ] and it prints " + res2);
+ }
+ }
+
+ ====
+ import static org.junit.Assert.*;
+ import org.junit.*;
+ import java.io.*;
+ import java.util.*;
+
+ public class RunestoneTests extends CodeTestHelper
+ {
+ @Test
+ public void testRunGetDelimitersList()
+ {
+ Delimiters d1 = new Delimiters("[", "]");
+ String[] tokens = {"[", "[", "x", "]", "]", "+ 5"};
+ ArrayList,
, ] and it prints [,
, ]\n";
+ boolean passed = getResults(expect, output, "Expected output from main");
+ assertTrue(passed);
+ }
+
+ @Test
+ public void checkCodeContains1()
+ {
+ // check accessor method getDelimitersList()
+ boolean passed =
+ checkCodeContains(
+ "correct getDelimitersList method header",
+ "ArrayList
ArrayList class which implements the ``List`` interface.
-
- Which of the following is *false* about an interface?
-
.. mchoice:: qale_9
:practice: T
:answer_a: [2, 3]
diff --git a/_sources/Unit7-ArrayList/listHardMC.rst b/_sources/Unit7-ArrayList/listHardMC.rst
index 4ca7b8133..1e731a6bb 100644
--- a/_sources/Unit7-ArrayList/listHardMC.rst
+++ b/_sources/Unit7-ArrayList/listHardMC.rst
@@ -1,11 +1,11 @@
.. qnum::
:prefix: 7-11-3-
:start: 1
-
+
Hard Multiple Choice Questions
----------------------------------
-These problems are about the same or harder than those you will see on the AP CS A exam.
+These problems are about the same or harder than those you will see on the AP CSA exam.
.. mchoice:: qalh_1
:practice: T
@@ -15,22 +15,22 @@ These problems are about the same or harder than those you will see on the AP CS
:answer_d: [5, 3, 6]
:answer_e: [4, 5, 3, 6]
:correct: b
- :feedback_a: The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0.
- :feedback_b: The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1.
+ :feedback_a: The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0.
+ :feedback_b: The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1.
:feedback_c: The remove(1) doesn't remove the 1, it removes the value at index 1.
- :feedback_d: The 5 will be removed with the remove(1).
+ :feedback_d: The 5 will be removed with the remove(1).
:feedback_e: This would be true if remove(1) removed the item with that value, but it removes the item at that index.
What is in the list ``nums`` if it initially contained {5, 3, 1} and the following code is executed?
-
+
.. code-block:: java
-
+
nums.add(6);
nums.add(0,4);
nums.remove(1);
-
+
You can step through the code above by clicking on the following `Example-8-13-1 remove(0). Remember that it removes the object at the given index.
+ :feedback_c: This would be true if the set was an add.
+ :feedback_d: This would be true it it was remove(0). Remember that it removes the object at the given index.
:feedback_e: This would be true if the set was an add and if it was remove(0).
What is printed as a result of executing the following code segment?
-
+
.. code-block:: java
-
+
Listlist1.set(1,"d"); was list1.add(1,"d");
- :feedback_d: This would be true it list1.set(1,"d"); was list1.add(1,"d"); and if lists didn't allow duplicate objects.
+ :feedback_c: This would be true it list1.set(1,"d"); was list1.add(1,"d");
+ :feedback_d: This would be true it list1.set(1,"d"); was list1.add(1,"d"); and if lists didn't allow duplicate objects.
What is printed as a result of executing the following code segment?
-
+
.. code-block:: java
-
+
ListnumList.add(numList.size() - i, obj)
- :feedback_b: This would be true if it was mystery(1)
+ :feedback_b: This would be true if it was mystery(1)
:feedback_c: Each value is removed one at a time and added to the end of the list which results in the same list.
- :feedback_d: This would be true if it was mystery(2)
- :feedback_e: This would be true if it was mystery(4)
-
+ :feedback_d: This would be true if it was mystery(2)
+ :feedback_e: This would be true if it was mystery(4)
+
Assume that ``numList`` has been initialized with the following Integer objects: [0, 1, 2, 3, 4]. What is the value of ``numList`` after ``mystery(5)`` executes?
-
+
.. code-block:: java
-
+
private ListnumList.add(0, value)
:feedback_d: This would be true if the while loop was from 0 to one less than the size of the list.
- :feedback_e: This would be true if it was numList.add(i-1, value)
-
+ :feedback_e: This would be true if it was numList.add(i-1, value)
+
Assume that ``numList`` has been initialized with the following Integer objects: [5, 7, 8, 12]. Which of the following shows the values in ``numList`` after a call to ``mystery(11)``?
-
+
.. code-block:: java
-
- private List