diff --git a/book.toml b/book.toml index 11ba9a0..0666248 100644 --- a/book.toml +++ b/book.toml @@ -16,18 +16,10 @@ additional-js = ["ferris.js"] enable = true # whether or not to enable section folding level = 0 # the depth to start folding -[preprocessor.features] -command = "python3 features.py" -# Going to start writing the rest of the book -# Assuming this is true -toplevel_anonymous_class = true -# Not ready -simple_io = false -# Turn on when Java 21 released -java_21 = false - [output.html.playground] editable = true [output.html.code.hidelines] java = "~" +[output.html.code.hidelines] +java = "~" diff --git a/features.py b/features.py deleted file mode 100755 index 4eb409e..0000000 --- a/features.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python3 - -# This file is python, not Java. -# but we got enough people complaining that the repo in github showed 100% python -# that I just changed the extension to .java - I think its funny. We can replace -# this file if either a json library is added to java or someone wants to do all -# the setup to pull in a json lib. - -import json -import sys - -def preprocess_content(context, content): - options = context.get("config", {}).get("preprocessor", {}).get("features", {}) - newContent = [] - skipping = False - for line in content.splitlines(): - if skipping: - if line.strip() == "~ENDIF" or line.strip() == "~ ENDIF": - skipping = False - elif line.strip() == "~ELSE" or line.strip() == "~ ELSE": - skipping = False - elif line.strip().startswith("~IF ") or line.strip().startswith("~ IF "): - if not options.get(line.split(" ", 2)[1].strip(), False): - skipping = True - elif line.strip() == "~ENDIF" or line.strip() == "~ ENDIF": - continue - elif line.strip() == "~ELSE" or line.strip() == "~ ELSE": - skipping = True - continue - else: - if options.get("simple_io", False) and options.get("toplevel_anonymous_class", False): - newContent.append(line.replace("System.out.println", "printLine").replace("System.out.print", "print")) - else: - newContent.append(line) - - return "\n".join(newContent) - -def preprocess_section(context, section): - if "Chapter" in section: - section["Chapter"]["content"] = \ - preprocess_content(context, section["Chapter"]["content"]) - for sub_section in section["Chapter"].get("sub_items", []): - preprocess_section(context, sub_section) - -if __name__ == '__main__': - if len(sys.argv) > 1: - if sys.argv[1] == "supports": - sys.exit(0) - - json_input = json.load(sys.stdin) - context, book = json_input - - for section in book["sections"]: - preprocess_section(context, section) - - print(json.dumps(book)) diff --git a/ferris.js b/ferris.js index 0424fd8..f78ce4a 100644 --- a/ferris.js +++ b/ferris.js @@ -1,66 +1,65 @@ var ferrisTypes = [ - { - attr: 'does_not_compile', - title: 'This code does not compile!' - }, - { - attr: 'panics', - title: 'This code will crash!' - }, - { - attr: 'not_desired_behavior', - title: 'This code does not produce the desired behavior.' - } - ] - - document.addEventListener('DOMContentLoaded', () => { - for (var ferrisType of ferrisTypes) { - attachFerrises(ferrisType) - } - }) - - function attachFerrises(type) { - var elements = document.getElementsByClassName(type.attr) - - for (var codeBlock of elements) { - var lines = codeBlock.innerText.replace(/\n$/, '').split(/\n/).length - var size = 'large' - if (lines < 4) { - size = 'small' - } - - var container = prepareFerrisContainer(codeBlock, size == 'small') - container.appendChild(createFerris(type, size)) - } + { + attr: 'does_not_compile', + title: 'This code does not compile!' + }, + { + attr: 'panics', + title: 'This code will crash!' + }, + { + attr: 'not_desired_behavior', + title: 'This code does not produce the desired behavior.' + } +] + +document.addEventListener('DOMContentLoaded', () => { + for (var ferrisType of ferrisTypes) { + attachFerrises(ferrisType) } - - function prepareFerrisContainer(element, useButtons) { - var foundButtons = element.parentElement.querySelector('.buttons') - if (useButtons && foundButtons) { - return foundButtons +}) + +function attachFerrises(type) { + var elements = document.getElementsByClassName(type.attr) + + for (var codeBlock of elements) { + var lines = codeBlock.innerText.replace(/\n$/, '').split(/\n/).length + var size = 'large' + if (lines < 5) { + size = 'small' } - - var div = document.createElement('div') - div.classList.add('ferris-container') - - element.parentElement.insertBefore(div, element) - - return div + + var container = prepareFerrisContainer(codeBlock, size == 'small') + container.appendChild(createFerris(type, size)) } - - function createFerris(type, size) { - var a = document.createElement('a') - a.setAttribute('href', 'ch00-00-introduction.html#ferris') - a.setAttribute('target', '_blank') - - var img = document.createElement('img') - img.setAttribute('src', '../img/' + type.attr + '.svg') - img.setAttribute('title', type.title) - img.classList.add('ferris') - img.classList.add('ferris-' + size) - - a.appendChild(img) - - return a +} + +function prepareFerrisContainer(element, useButtons) { + var foundButtons = element.parentElement.querySelector('.buttons') + if (useButtons && foundButtons) { + return foundButtons } - \ No newline at end of file + + var div = document.createElement('div') + div.classList.add('ferris-container') + + element.parentElement.insertBefore(div, element) + + return div +} + +function createFerris(type, size) { + var a = document.createElement('a') + // a.setAttribute('href', 'ch00-00-introduction.html#ferris') + a.setAttribute('target', '_blank') + + var img = document.createElement('img') + img.setAttribute('src', '../img/' + type.attr + '.svg') + img.setAttribute('title', type.title) + img.classList.add('ferris') + img.classList.add('ferris-' + size) + + a.appendChild(img) + + return a +} diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 4aa6347..725b3cd 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -99,13 +99,16 @@ - [If](./branching_logic/if.md) - [Nested Ifs](./branching_logic/nested_ifs.md) - [Else](./branching_logic/else.md) + - [Else](./branching_logic/else.md) - [Else If](./branching_logic/else_if.md) - [Relation to Delayed Assignment](./branching_logic/relation_to_delayed_assignment.md) - [Scoped Variables](./branching_logic/scoped_variables.md) + - [Scoped Variables](./branching_logic/scoped_variables.md) - [Conditional Operator](./branching_logic/conditional_operator.md) - [Boolean Expressions](./branching_logic/boolean_expressions.md) - [Challenges](./branching_logic/challenges.md) + - [Loops](./loops.md) - [While](./loops/while.md) - [Endless Loops](./loops/endless_loops.md) @@ -169,6 +172,7 @@ - [Scope](./methods/scope.md) - [main](./methods/main.md) - [Challenges](./methods/challenges.md) + - [Arguments](./arguments.md) - [Declaration](./arguments/declaration.md) @@ -180,26 +184,23 @@ - [Inferred Types](./arguments/inferred_types.md) - [Challenges](./arguments/challenges.md) -- [Return](./return_values.md) - - [Return Values](./return_values/return_values.md) - - [Conversion](./return_values/conversion.md) +- [Return Values](./return_values.md) + - [Declaration](./return_values/declaration.md) + - [Return Statement](./return_values/return_statement.md) + - [Exhaustiveness](./return_values/exhaustiveness.md) - [void](./return_values/void.md) + - [Return in void methods](./return_values/return_in_void_methods.md) + - [Conversion](./return_values/conversion.md) - [Unreachable Statements](./return_values/unreachable_statements.md) - - [Pure Functions](./return_values/pure_functions.md) - - [Impure Functions](./return_values/impure_functions.md) # Data Types III -- [Identity Types](./identity_types.md) - - [Comparison with ==](./identity_types/comparison_with_equalsequals.md) -- [Primitive Types](./primitive_types.md) - [null](./null.md) - [Null as Absence](./null/null_as_absence.md) + - [Null as Unknown](./null/null_as_unknown.md) - [Checking for null](./null/checking_for_null.md) - - [Field Access](./null/field_access.md) - - [Instance Methods](./null/instance_methods.md) + - [NullPointerException](./null/null_pointer_exception.md) - [Boxed Primitives](./boxed_primitives.md) - - [Primitive Types](./boxed_primitives/primitive_types.md) - [Integer](./boxed_primitives/integer.md) - [Double](./boxed_primitives/double.md) - [Character](./boxed_primitives/character.md) @@ -208,39 +209,100 @@ - [Boxing Conversion](./boxed_primitives/boxing_conversion.md) - [Arrays of Boxed Primitives](./boxed_primitives/arrays_of_boxed_primitives.md) - [Challenges](./boxed_primitives/challenges.md) + - [Challenges](./boxed_primitives/challenges.md) - [Arrays II](./arrays_ii.md) + - [Initializion with Size](./arrays_ii/initialization_with_size.md) - [Default Values](./arrays_ii/default_values.md) - - [Populate Array]() + - [Populate Arrays](./arrays_ii/populate_arrays.md) # Code Structure II - [Classes](./classes.md) - + - [The meaning of the word Class](./classes/the_meaning_of_the_word_class.md) - [Class Declaration](./classes/class_declaration.md) - - [User Defined Types](./classes/user_defined_types.md) - - [Naming Classes](./classes/naming_classes.md) - - [Field Declaration](./classes/field_declaration.md) - - [Field Access](./classes/field_access) - - [Naming Fields](./classes/naming_fields.md) - - [new](./classes/new.md) - - [Zero Values](./classes/zero_values.md) + - [Naming](./classes/naming.md) + - [Instances](./classes/instances.md) + - [Fields](./classes/fields.md) + - [Field Initialization](./classes/field_initialization.md) + - [Field Access](./classes/field_access.md) + - [Field Default Values](./classes/field_default_values.md) - [Aliasing](./classes/aliasing.md) - - [null](./classes/null.md) + - [Return Multiple Values](./classes/return_multiple_values.md) -- [Constructors](./constructors.md) +- [Instance Methods](./instance_methods.md) + - [Invocation](./instance_methods/invocation.md) + - [Arguments](./instance_methods/arguments.md) + - [Field Access](./instance_methods/field_access.md) + - [Field Updates](./instance_methods/field_updates.md) + - [Derived Values](./instance_methods/derived_values.md) + - [Invoke Other Methods](./instance_methods/invoke_other_methods.md) + - [this](./instance_methods/this.md) + - [Disambiguation](./instance_methods/disambiguation.md) + - [Clarity](./instance_methods/clarity.md) + +# Data Types IV + +- [Enums](./enums.md) + - [Declaration](./enums/declaration.md) + - [Variants](./enums/variants.md) + - [Naming](./enums/naming.md) + - [Usage](./enums/usage.md) + - [Equality](./enums/equality.md) + - [Comparison to boolean](./enums/comparison_to_boolean.md) + +# Control Flow III + +- [Exceptions](./exceptions.md) + - [throw](./exceptions/throw.md) + - [Messages](./exceptions/messages.md) + - [Stack Traces](./exceptions/stack_traces.md) + - [try/catch](./exceptions/try_catch.md) +- [Switch](./switch.md) + - [Case and Default](./switch/case_and_default.md) + - [Strings](./switch/strings.md) + - [ints](./switch/ints.md) + - [Enums](./switch/enums.md) + - [Omitted Default](./switch/omitted_default.md) + - [Exhaustiveness](./switch/exhaustiveness.md) + - [Combining Cases](./switch/combining_cases.md) + - [null](./switch/null.md) + +# Code Structure III - - [this](./constructors/this.md) +- [Constructors](./constructors.md) + - [Declaration](./constructors/declaration.md) - [The Default Constructor](./constructors/the_default_constructor.md) + - [Arguments](./constructors/arguments.md) - [Final Fields](./constructors/final_fields.md) - - [Multiple Constructors](./constructors/multiple_constructors.md) + - [Invariants](./constructors/invariants.md) + - [Overloads](./constructors/overloads.md) + - [Delegation](./constructors/delegation.md) + + + + - ```java void main() { System.out.println("Hello, World"); } ``` -~ELSE +## repl.it -```java -public class Main { - public static void main(String[] args) { - System.out.println("Hello, World"); - } -} -``` +[replit.com](https://replit.com) is a pretty common choice for teachers because +they will be able to give you assignments and have you share back your results. +It is also a decent option if your school only provides you with Chromebooks +or similar. + +It requires an internet connection and you will have to make an account, but +otherwise it is fairly convenient. + +If you are in school and your teacher has helped you get set up in some other +way it is okay to skip this section and just do it the way you were shown. -~ENDIF -## Step 1. Make an account +### Step 1. Make an account Go to [replit.com](https://replit.com) and find the "Sign Up" button. Websites change every now and then so these screenshots might be out of date. @@ -63,7 +44,7 @@ Click it and sign up for an account. alt="Picture of the sign up form on replit's website" width = "200"> -## Step 2. Create a Java REPL +### Step 2. Create a Java REPL Find the "Create REPL" button and click it. @@ -82,27 +63,19 @@ Find the Java template and click "Create". alt="Filled in create from template menu on replit" width = "200"> -## Step 3. Run code +### Step 3. Run code You should land on a screen with a big green run button, an open file called "Main.java", and a blank window labeled "console". Picture of an unran hello world program Click it and you should see the text `Hello, world!` appear under the console window. Picture of a hello world program after running diff --git a/src/img/Agent.svg b/src/img/Agent.svg new file mode 100644 index 0000000..1c08b91 --- /dev/null +++ b/src/img/Agent.svg @@ -0,0 +1,292 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/Boxer.svg b/src/img/Boxer.svg new file mode 100644 index 0000000..9e5c00a --- /dev/null +++ b/src/img/Boxer.svg @@ -0,0 +1,1030 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/ChezDuke.svg b/src/img/ChezDuke.svg new file mode 100644 index 0000000..2ecce97 --- /dev/null +++ b/src/img/ChezDuke.svg @@ -0,0 +1,432 @@ + + + + + + + + + + diff --git a/src/img/NyaNya.svg b/src/img/NyaNya.svg new file mode 100644 index 0000000..56bd253 --- /dev/null +++ b/src/img/NyaNya.svg @@ -0,0 +1,260 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/PalmTree.svg b/src/img/PalmTree.svg new file mode 100644 index 0000000..279d939 --- /dev/null +++ b/src/img/PalmTree.svg @@ -0,0 +1,764 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/Paper.svg b/src/img/Paper.svg new file mode 100644 index 0000000..3dcafee --- /dev/null +++ b/src/img/Paper.svg @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/Wave.svg b/src/img/Wave.svg new file mode 100644 index 0000000..4f2fc39 --- /dev/null +++ b/src/img/Wave.svg @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/does_not_compile.svg b/src/img/does_not_compile.svg index 48b7b4d..c85fee7 100644 --- a/src/img/does_not_compile.svg +++ b/src/img/does_not_compile.svg @@ -1,72 +1,25 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/does_not_compile_ferris.svg b/src/img/does_not_compile_ferris.svg new file mode 100644 index 0000000..48b7b4d --- /dev/null +++ b/src/img/does_not_compile_ferris.svg @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/img/panics.svg b/src/img/panics.svg index be55f5e..9a0a105 100644 --- a/src/img/panics.svg +++ b/src/img/panics.svg @@ -1,70 +1,20 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/img/panics_ferris.svg b/src/img/panics_ferris.svg new file mode 100644 index 0000000..be55f5e --- /dev/null +++ b/src/img/panics_ferris.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/instanc b/src/instanc new file mode 100644 index 0000000..7eff5f5 --- /dev/null +++ b/src/instanc @@ -0,0 +1 @@ +# Invoke Other Methods diff --git a/src/instance_methods.md b/src/instance_methods.md index d8122d8..e499cb0 100644 --- a/src/instance_methods.md +++ b/src/instance_methods.md @@ -1 +1,23 @@ # Instance Methods + +In addition to having fields, classes can also have their own method +definitions. + +These look the same as the method definitions you've +seen so far, they are just put within a class definition.[^kermitangry] + +```java +class Muppet { + String name; + + void freakOut() { + System.out.println("**ANGRY KERMIT NOISES**") + } +} +``` + +We call these instance methods because you need an instance of the class in order +to call the method. + +[^kermitangry]: If you haven't seen the muppets this might have go over your head, +but Kermit [randomly gets really mad.](https://www.youtube.com/watch?v=SVDgHEg2jnY) \ No newline at end of file diff --git a/src/instance_methods/arguments.md b/src/instance_methods/arguments.md new file mode 100644 index 0000000..b0f6f78 --- /dev/null +++ b/src/instance_methods/arguments.md @@ -0,0 +1,22 @@ +# Arguments + +Instance methods can take arguments the same as the methods you have +seen so far. + +```java +class Muppet { + String name; + + void singLyric(int verse) { + if (verse == 1) { + System.out.println("Why are there so many"); + } + else if (verse == 2) { + System.out.println("Songs about rainbows"); + } + else { + System.out.println("And what's on the other side?"); + } + } +} +``` \ No newline at end of file diff --git a/src/instance_methods/clarity.md b/src/instance_methods/clarity.md new file mode 100644 index 0000000..dd1085e --- /dev/null +++ b/src/instance_methods/clarity.md @@ -0,0 +1,30 @@ +# Clarity + +Another reason you might want to use `this` is for code clarity. + +It is a lot easier to know that a particular line refers to a field +or method on the same class if there is an explicit `this.` before +the reference.[^preference] + +```java +class Elmo { + int age; + + void sayHello() { + System.out.println("Hi, I'm Elmo"); + System.out.print("I am "); + System.out.print(this.age); + System.out.println(" years old."); + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + elmo.sayHello(); +} +``` + +[^preference]: This is very much a personal preference thing. I generally choose to write +`this.` whenever I am able to for this reason. \ No newline at end of file diff --git a/src/instance_methods/derived_values.md b/src/instance_methods/derived_values.md index 93afde7..8228ee0 100644 --- a/src/instance_methods/derived_values.md +++ b/src/instance_methods/derived_values.md @@ -1 +1,24 @@ # Derived Values + +A common use for methods is to provide a value that is derived from +the values of other fields. + +```java +class Elmo { + int age; + + int nextAge() { + return age + 1; + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + System.out.println("Elmo is " + elmo.age + " right now,"); + System.out.println("but next year Elmo will be " + elmo.nextAge()); +} +``` + +Which is useful for situations like where you store someones first and last name \ No newline at end of file diff --git a/src/instance_methods/disambiguation.md b/src/instance_methods/disambiguation.md new file mode 100644 index 0000000..d768fa5 --- /dev/null +++ b/src/instance_methods/disambiguation.md @@ -0,0 +1,28 @@ +# Disambiguation + +One reason you might need to use `this` is if the name +of an argument to a method is the same as the name of a field. + +```java +class Elmo { + int age; + + boolean isOlderThan(int age) { + return this.age > age; + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + // true + System.out.println(elmo.isOlderThan(2)); +} +``` + +If you didn't do this, it would be ambiguous whether you were referring to the field +or the argument. This removes the ambiguity.[^javanotconfused] + +[^javanotconfused]: Really it isn't ambiguous for Java. It will just think you are referring to the argument. +It is ambiguous from the perspective of a human being reading the code though. \ No newline at end of file diff --git a/src/instance_methods/field_access.md b/src/instance_methods/field_access.md new file mode 100644 index 0000000..b062662 --- /dev/null +++ b/src/instance_methods/field_access.md @@ -0,0 +1,26 @@ +# Field Access + +Within an instance method's definition, you can access the values +of any fields declared in the class by just writing their name. + +```java +class Elmo { + int age; + + void sayHello() { + System.out.println("Hi, I'm Elmo"); + System.out.print("I am "); + + // You can use elmo's age by just writing "age" + System.out.print(age); + System.out.println(" years old."); + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + elmo.sayHello(); +} +``` \ No newline at end of file diff --git a/src/instance_methods/field_updates.md b/src/instance_methods/field_updates.md new file mode 100644 index 0000000..9f03007 --- /dev/null +++ b/src/instance_methods/field_updates.md @@ -0,0 +1,30 @@ +# Field Updates + +You can also update the value of any field from within an instance +method the same as if it were a local variable. + +```java +class Elmo { + int age; + + void sayHello() { + System.out.println("Hi, I'm Elmo"); + System.out.print("I am "); + System.out.print(age); + System.out.println(" years old."); + } + + void haveBirthday() { + age = age + 1; + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + elmo.sayHello(); + elmo.haveBirthday(); + elmo.sayHello(); +} +``` \ No newline at end of file diff --git a/src/instance_methods/invocation.md b/src/instance_methods/invocation.md index 3dae992..cd86fc3 100644 --- a/src/instance_methods/invocation.md +++ b/src/instance_methods/invocation.md @@ -1 +1,20 @@ # Invocation + +To invoke an instance method you first need an instance of the class. + +You then write `.` followed by the name of the instance method and a list of arguments.[^elmo] + +```java +class Elmo { + void talkAboutRocko() { + System.out.println("ROCKO'S NOT ALIVE!!") + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.talkAboutRocko(); +} +``` + +[^elmo]: Daily reminder that Elmo absolutely [hates Rocko](https://www.youtube.com/watch?v=DFBMcwaSdns) \ No newline at end of file diff --git a/src/instance_methods/invoke_other_methods.md b/src/instance_methods/invoke_other_methods.md new file mode 100644 index 0000000..d15d11c --- /dev/null +++ b/src/instance_methods/invoke_other_methods.md @@ -0,0 +1,29 @@ +# Invoke Other Methods + +Inside of an instance method you can invoke other instance methods +on the same class by writing their name and providing any needed arguments. + +```java +class Elmo { + int age; + + void sayHello() { + System.out.println("Hi, I'm Elmo"); + System.out.print("I am "); + System.out.print(age); + System.out.println(" years old."); + } + + void startTheShow(String showName) { + sayHello(); + System.out.println("Welcome to " + showName); + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + elmo.startTheShow("Sesame Street"); +} +``` \ No newline at end of file diff --git a/src/instance_methods/this.md b/src/instance_methods/this.md index d742220..5b56b55 100644 --- a/src/instance_methods/this.md +++ b/src/instance_methods/this.md @@ -1 +1,32 @@ # this + +Within an instance method, you have access to a magic variable called `this`. + +`this` is a variable that contains the current instance of the class. + +You can use `this` to access fields or invoke any method. + +```java +class Elmo { + int age; + + void sayHello() { + System.out.println("Hi, I'm Elmo"); + System.out.print("I am "); + System.out.print(this.age); + System.out.println(" years old."); + } + + void startTheShow(String showName) { + this.sayHello(); + System.out.println("Welcome to " + showName); + } +} + +void main() { + Elmo elmo = new Elmo(); + elmo.age = 3; + + elmo.startTheShow("Sesame Street"); +} +``` \ No newline at end of file diff --git a/src/integers/addition.md b/src/integers/addition.md index 007006f..ca2bade 100644 --- a/src/integers/addition.md +++ b/src/integers/addition.md @@ -3,6 +3,7 @@ You can add any two `int`s using the `+` operator. ```java +~void main() { int x = 5; // y will be 6 int y = x + 1; @@ -12,15 +13,18 @@ int z = x + y; System.out.println(x); System.out.println(y); System.out.println(z); +~} ``` Adding a negative number does the same thing as subtraction. ```java +~void main() { int x = 5; // y will be 1 int y = x + -4; System.out.println(x); System.out.println(y); +~} ``` diff --git a/src/integers/chained_comparisons.md b/src/integers/chained_comparisons.md index 81d1d4f..334e010 100644 --- a/src/integers/chained_comparisons.md +++ b/src/integers/chained_comparisons.md @@ -4,13 +4,13 @@ When writing an expression in math to say something along the lines of "`x` is greater than zero and less than 5," it is natural to put that `x` in the middle of both operators like so. -```text +```text,no_run 0 < x < 5 ``` This does not work in Java. In order to "chain" comparisons like this, you should combine the results of comparisons using the `&&` operator. -```java +```java,no_run boolean xInRange = 0 < x && x < 5; ``` diff --git a/src/integers/challenges.md b/src/integers/challenges.md index ff13d80..a4be09f 100644 --- a/src/integers/challenges.md +++ b/src/integers/challenges.md @@ -9,9 +9,7 @@ Remember the rules for this are What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 5; int y = 8; @@ -19,27 +17,11 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 5; - int y = 8; - System.out.println(x + y); - } -} -``` - -~ENDIF - ## Challenge 2 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 5; x--; @@ -49,22 +31,6 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 5; - x--; - x--; - x = x + x; - System.out.println(x); - } -} -``` - -~ENDIF - ## Challenge 3 Make it so that this program correctly determines if the numbers are even or not. @@ -72,9 +38,7 @@ Make it so that this program correctly determines if the numbers are even or not Assume that the values of `x`, `y`, and `z` could be changed. Don't just write out literally `true` and `false` for their current values. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 5; int y = 4; @@ -91,62 +55,23 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 5; - int y = 4; - int z = 98; - - boolean xIsEven = < CODE HERE >; - System.out.println(xIsEven); - - boolean yIsEven = < CODE HERE >; - System.out.println(yIsEven); - - boolean zIsEven = < CODE HERE >; - System.out.println(zIsEven); - } -} -``` - -~ENDIF - ## Challenge 4 Try dividing a number by zero. What happens? Write down your guess and then try running the program below to see. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { System.out.println(5 / 0); } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - System.out.println(5 / 0); - } -} -``` - -~ENDIF - ## Challenge 5 What can you write in the spot marked that will make the program output 2? -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 5; int y = ; @@ -154,27 +79,11 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 5; - int y = ; - System.out.println(x + y); - } -} -``` - -~ENDIF - ## Challenge 6 What is the output of this code.[^fbarticle] -~IF toplevel_anonymous_class - -```java +```java,editable void main() { System.out.println( 6 / 2 * (1 + 2) @@ -182,18 +91,4 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - System.out.println( - 6 / 2 * (1 + 2) - ); - } -} -``` - -~ENDIF - [^fbarticle]: [Now get in a fight with your relatives about it](https://slate.com/technology/2013/03/facebook-math-problem-why-pemdas-doesnt-always-give-a-clear-answer.html) diff --git a/src/integers/comparison.md b/src/integers/comparison.md index d484cff..d3233b3 100644 --- a/src/integers/comparison.md +++ b/src/integers/comparison.md @@ -5,14 +5,14 @@ In addition to comparing for equality with `==` and `!=`, `int`s can be compared `>` will evaluate to true if the number on the left is greater than the one on the right. -```java +```java,no_run boolean willBeTrue = 5 > 2; boolean willBeFalse = 2 > 5; ``` `<` will evaluate to true if the number on the right is greater than the one on the left. -```java +```java,no_run boolean willBeFalse = 5 < 2; boolean willBeTrue = 2 < 5; ``` @@ -20,7 +20,7 @@ boolean willBeTrue = 2 < 5; If you went to public school like I did, you should be used to imagining that the `>` was the jaw of a shark. Whatever direction the Jaws are facing, thats the one that would need to be bigger for the statement to be true.[^sharks] -```java +```java,no_run // true if the shark is facing the bigger number // false otherwise. boolean result = 9 🦈 5; @@ -28,14 +28,14 @@ boolean result = 9 🦈 5; `>=` behaves the same as `>` except `>=` will evaluate to `true` if the numbers are identical, `>` will not. -```java +```java,no_run boolean willBeTrue = 5 >= 5; boolean willBeFalse = 5 > 5; ``` `<=` has the same relationship to `<` as `>=` does to `>`. -```java +```java,no_run boolean willBeTrue = 5 <= 5; boolean willBeFalse = 5 < 5; ``` diff --git a/src/integers/division.md b/src/integers/division.md index bdf0f0e..87f8ce6 100644 --- a/src/integers/division.md +++ b/src/integers/division.md @@ -3,12 +3,14 @@ You can divide any two `int`s using the `/` operator. ```java +~void main() { int x = 8; // y will be 4 int y = x / 2; System.out.println(x); System.out.println(y); +~} ``` Division with integers gives results in only the [quotient](https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-quotient-remainder-theorem) of the result, not the remainder. @@ -16,6 +18,7 @@ Division with integers gives results in only the [quotient](https://www.khanacad So `5 / 2` does not result in `2.5`, but instead just `2`. ```java +~void main() { // 5 / 2 is not 2.5, but instead 2. int x = 5 / 2; // 13 / 3 is not 4.3333, but instead 4. @@ -23,4 +26,5 @@ int y = 13 / 3; System.out.println(x); System.out.println(y); +~} ``` diff --git a/src/integers/equality.md b/src/integers/equality.md index 4119eb0..931f100 100644 --- a/src/integers/equality.md +++ b/src/integers/equality.md @@ -26,8 +26,10 @@ It is very important to remember that a single `=` does an assignment. Two equal The opposite check, whether things are not equal, can be done with `!=`. ```java +~void main() { // 1 is never equal to 2 // this will be true boolean universeOkay = 1 != 2; System.out.println(universeOkay); +~} ``` diff --git a/src/integers/limits.md b/src/integers/limits.md index d1908e5..425b755 100644 --- a/src/integers/limits.md +++ b/src/integers/limits.md @@ -12,20 +12,24 @@ the type `int` can represent numbers from -231 to 231 - 1. If you try to directly write out a number that is outside of that range, Java will not let you. -```java +```java,does_not_compile +~void main() { // This will not run int tooBig = 999999999999; +~} ``` If you do math that should produce a larger number than is representable, the value will "loop around." ```java +~void main() { // This is the value of 2^31 - 1 int atLimit = 2147483647; // The value will "loop around" to -2^31 int beyondLimit = atLimit + 1; // This will output -2147483648 System.out.println(beyondLimit); +~} ``` There are other types which can represent a larger range of integers, as well as types diff --git a/src/integers/multiplication.md b/src/integers/multiplication.md index a92a890..bd20c08 100644 --- a/src/integers/multiplication.md +++ b/src/integers/multiplication.md @@ -3,6 +3,7 @@ You can multiply any two `int`s using the `*` operator. ```java +~void main() { // x will be 15 int x = 3 * 5; // y will be 75 @@ -13,4 +14,5 @@ int z = x * y; System.out.println(x); System.out.println(y); System.out.println(z); +~} ``` diff --git a/src/integers/operator_precedence.md b/src/integers/operator_precedence.md index ed1f695..6384a87 100644 --- a/src/integers/operator_precedence.md +++ b/src/integers/operator_precedence.md @@ -9,6 +9,7 @@ Parentheses can be used to control this order. None of this should be a surprise if you learned [PEMDAS](https://www.khanacademy.org/math/cc-seventh-grade-math/cc-7th-negative-numbers-multiply-and-divide/cc-7th-order-of-operations/v/introduction-to-order-of-operations) in school. ```java +~void main() { // Following the order of operations: // 2 * 3 + 3 * 9 / 2 - 2 @@ -28,14 +29,18 @@ None of this should be a surprise if you learned [PEMDAS](https://www.khanacadem // and the final result is 17; int result = 2 * 3 + 3 * 9 / 2 - 2; System.out.println(result); +~} ``` The `==`, `!=`, `>`, `<`, `>=`, and `<=` operators play a part here too[^theyalldo]. They all have a lower precedence order than all the math operators, so you can put them in the middle of any two math expressions. ```java +~void main() { // The == check happens last. boolean areThingsSame = 3 * (4 - 1 + 3) * 4 == 5 * 3 + 1 * 3 * 9; +System.out.println(areThingsSame); +~} ``` [^theyalldo]: Every operator in the language has a defined order of operations with respect to all of the others. I am just showing them to you as they become relevant. diff --git a/src/integers/reassignment.md b/src/integers/reassignment.md index be49064..b00359a 100644 --- a/src/integers/reassignment.md +++ b/src/integers/reassignment.md @@ -6,6 +6,7 @@ before the reassignment can be used to compute the new value. This is true for all data types, but it is easiest to demonstrate with numbers. ```java +~void main() { int x = 1; System.out.println(x); @@ -18,6 +19,7 @@ System.out.println(x); // 12 is the new value of x. x = x * x * 3; System.out.println(x); +~} ``` This property was used in the previous example for the `%` operator, but I think it worth calling attention to even if it is "intuitive". diff --git a/src/integers/remainder.md b/src/integers/remainder.md index e1b7de9..97250df 100644 --- a/src/integers/remainder.md +++ b/src/integers/remainder.md @@ -4,6 +4,7 @@ To get the remainder of the division between two integers you can use the `%` op This is called the "modulo operator." ```java +~void main() { int x = 5; // The remainder of 5 / 2 is 1 // y will be 1 @@ -15,6 +16,7 @@ int z = x % 3; System.out.println(x); System.out.println(y); System.out.println(z); +~} ``` A common use for this is to make numbers "go in a circle." @@ -22,6 +24,7 @@ A common use for this is to make numbers "go in a circle." For instance, say you wanted to count from 0 up to 3 and then go back to 0. ```java +~void main() { int value = 0; System.out.println(value); @@ -48,6 +51,7 @@ value = (value + 1) % 3; System.out.println(value); // and so on. +~} ``` The fact that all the reassignments of value look identical is something that will be useful in tandem diff --git a/src/integers/shorthands_for_reassignment.md b/src/integers/shorthands_for_reassignment.md index d77b04b..112a402 100644 --- a/src/integers/shorthands_for_reassignment.md +++ b/src/integers/shorthands_for_reassignment.md @@ -4,16 +4,19 @@ A very common thing to do is to take the current value of a variable, perform so computed value back into the variable. ```java +~void main() { int x = 2; System.out.println(x); -x = x * 5 // 10 +x = x * 5; // 10 System.out.println(x); +~} ``` As such, there is a dedicated way to do just that. ```java +~void main() { int x = 1; // This is the same as @@ -26,7 +29,7 @@ x *= 4; // This is the same as // x = x - (x * 5) -x -= (x * 5) +x -= (x * 5); // This is the same as // x = x / 6 @@ -38,12 +41,14 @@ x %= 3; // Pop quiz! System.out.println(x); +~} ``` Of note is that adding or subtracting exactly 1 is common enough that it has its own special shorthand. ```java +~void main() { int x = 0; System.out.println(x); @@ -58,4 +63,5 @@ System.out.println(x); // x -= 1; x--; System.out.println(x); +~} ``` diff --git a/src/integers/subtraction.md b/src/integers/subtraction.md index 7422a2e..109a097 100644 --- a/src/integers/subtraction.md +++ b/src/integers/subtraction.md @@ -3,6 +3,7 @@ You can subtract any two `int`s using the `-` operator. ```java +~void main() { int x = 5; // y will be 4 int y = x - 1; @@ -12,15 +13,18 @@ int z = x - y; System.out.println(x); System.out.println(y); System.out.println(z); +~} ``` Subtracting a negative number does the same thing as addition. ```java +~void main() { int x = 5; // y will be 9 int y = x - -4; System.out.println(x); System.out.println(y); +~} ``` diff --git a/src/loops/break.md b/src/loops/break.md index 830f828..fbb9c03 100644 --- a/src/loops/break.md +++ b/src/loops/break.md @@ -6,6 +6,7 @@ to `false`. This can be bypassed by using the `break` statement. ```java +~void main() { int x = 5; while (x > 0) { if (x == 2) { @@ -17,6 +18,7 @@ while (x > 0) { System.out.println( "Final value of x is " + x ); +~} ``` If a `break` is reached, the code in the loop stops running immediately. @@ -26,6 +28,7 @@ This can be useful in a variety of situations, but notably it is the only way to from an otherwise endless loop. ```java +~void main() { while (true) { System.out.println( "The people started singing it not knowing what it was" @@ -34,4 +37,5 @@ while (true) { // Will immediately leave the loop break; } +~} ``` diff --git a/src/loops/challenges.md b/src/loops/challenges.md index a8653ce..8ab05c3 100644 --- a/src/loops/challenges.md +++ b/src/loops/challenges.md @@ -18,33 +18,20 @@ Remember the rules for this are Write code that outputs every number from `1` to `10`. -~IF toplevel_anonymous_class -```java +```java,editable void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - - } -} -``` - -~ENDIF ## Challenge 2 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class -```java +```java,editable void main() { int x = 0; while (x < 10) { @@ -54,29 +41,12 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 0; - while (x < 10) { - System.out.println(x); - x++; - } - } -} -``` - -~ENDIF ## Challenge 3 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 0; while (x <= 10) { @@ -86,29 +56,11 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 0; - while (x <= 10) { - System.out.println(x); - x++; - } - } -} -``` - -~ENDIF - ## Challenge 4 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 0; while (x < 10) { @@ -121,32 +73,12 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 0; - while (x < 10) { - if (x % 3 == 0) { - break; - } - System.out.println(x); - x++; - } - } -} -``` - -~ENDIF ## Challenge 5 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 0; while (x < 10) { @@ -159,33 +91,12 @@ void main() { } ``` -~ELSE - -```java -public class Main { - - public static void main(String[] args) { - int x = 0; - while (x < 10) { - if (x % 3 == 0) { - continue; - } - System.out.println(x); - x++; - } - } -} -``` - -~ENDIF ## Challenge 6 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { int x = 1; while (x < 10) { @@ -200,56 +111,16 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 1; - while (x < 10) { - int y = 2; - while (y < 5) { - System.out.println(x * y); - y++; - } - - x++; - } - } -} -``` - -~ENDIF - ## Challenge 7 What will this program output when run? Write down your guess and then try running it. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - int x = 0; - String scream = "a"; - while (!scream.equals("aaaaaaaa")) { - scream = scream + "a"; - System.out.println(x); - System.out.println(scream); - } - } -} -``` - -~ENDIF ## Challenge 8 @@ -267,28 +138,12 @@ e t ``` -~IF toplevel_anonymous_class - -```java +```java,editable void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Change this value to test your code. - String name = "Bridget"; - - // - } -} -``` - -~ENDIF ## Challenge 9 @@ -308,9 +163,7 @@ a S ``` -~IF toplevel_anonymous_class - -```java +```java,editable void main() { // Change this value to test your code. String name = "Samantha"; @@ -319,20 +172,6 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Change this value to test your code. - String name = "Samantha"; - - // - } -} -``` - -~ENDIF ## Challenge 10 @@ -377,9 +216,7 @@ If the initial number is `15` you should have this as output. 1 ``` -~IF toplevel_anonymous_class - -```java +```java,editable void main() { // Change this value to test your code. int n = 15; @@ -388,44 +225,17 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Change this value to test your code. - int n = 15; - - // - } -} -``` - -~ENDIF ## Challenge 11 Write code that outputs every third number from `37` to `160`. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - - } -} -``` - -~ENDIF ## Challenge 12 @@ -433,9 +243,7 @@ Write code that outputs the number of vowels in `name`. Treat `y` as a vowel. Treat the characters `a`, `A`, `e`, `E`, `i`, `I`, `o`, `O`, `u`, `U`, `y`, and `Y` as vowels. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { // Change this value to test your code. String name = "Damian"; @@ -444,20 +252,6 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Change this value to test your code. - String name = "Damian"; - - // - } -} -``` - -~ENDIF ## Challenge 13 @@ -468,9 +262,7 @@ same. Make sure to not treat non-alphabetic characters like `!` and `?` as consonants. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { // Change this value to test your code. String name = "Messi"; @@ -479,29 +271,13 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Change this value to test your code. - String name = "Messi"; - - // - } -} -``` - -~ENDIF ## Challenge 14 Rewrite the following code to not have the `shouldBreak` variable and instead to use a labeled break. -~IF toplevel_anonymous_class - -```java +```java,editable void main() { // Don't think too hard about what these numbers mean. int x = 3; @@ -525,32 +301,3 @@ void main() { } ``` -~ELSE - -```java -public class Main { - public static void main(String[] args) { - // Don't think too hard about what these numbers mean. - int x = 3; - int y = 0; - - boolean shouldBreak = false; - while (shouldBreak && x < 100) { - while (y < 100) { - System.out.println("x is " + x); - System.out.println("y is " + y); - x = x * y; - if (x == 0) { - shouldBreak = true; - break; - } - y++; - } - } - - System.out.println("Done"); - } -} -``` - -~ENDIF diff --git a/src/loops/continue.md b/src/loops/continue.md index 9ce9b18..fc4f700 100644 --- a/src/loops/continue.md +++ b/src/loops/continue.md @@ -5,6 +5,7 @@ Unless there is a `break`, while loops will usually run all the code in their bo The only other situation this will not happen is if a `continue` statement is reached. ```java +~void main() { // Will output a message for every number except 4 int x = 5; while (x > 0) { @@ -14,6 +15,7 @@ while (x > 0) { System.out.println(x + " is a good number"); x--; } +~} ``` If a `continue` is reached the code in the loop stops running immediately but, unlike `break`, diff --git a/src/loops/counting_down.md b/src/loops/counting_down.md index 4d0be13..4110733 100644 --- a/src/loops/counting_down.md +++ b/src/loops/counting_down.md @@ -8,21 +8,25 @@ number, but with a loop whose condition is that the number is greater than the n to stop at, and a line at the bottom of the loop which decrements the current number. ```java +~void main() { int currentNumber = 100; while (currentNumber >= 1) { System.out.println(currentNumber); currentNumber--; } +~} ``` Similar to when counting up if the condition was not `currentNumber >= 1` and instead was `currentNumber > 1`, the loop would stop at `2` ```java +~void main() { int currentNumber = 100; // Stops at 2 while (currentNumber > 1) { System.out.println(currentNumber); currentNumber--; } +~} ``` diff --git a/src/loops/counting_up.md b/src/loops/counting_up.md index 48805b5..030fc74 100644 --- a/src/loops/counting_up.md +++ b/src/loops/counting_up.md @@ -7,11 +7,13 @@ number, a loop whose condition is that the number is less than the number you wa to stop at, and a line at the bottom of the loop which increments the current number. ```java +~void main() { int currentNumber = 1; while (currentNumber <= 100) { System.out.println(currentNumber); currentNumber++; } +~} ``` Take note that in this example the condition is `currentNumber <= 100`, so the code in the @@ -19,10 +21,12 @@ loop will run when `currentNumber` is equal to `100`. If the condition was `curr it would stop at `99`. ```java +~void main() { int currentNumber = 1; // Stops at 99 while (currentNumber < 100) { System.out.println(currentNumber); currentNumber++; } +~} ``` diff --git a/src/loops/do_while.md b/src/loops/do_while.md index fdbcebe..711b119 100644 --- a/src/loops/do_while.md +++ b/src/loops/do_while.md @@ -3,17 +3,19 @@ One variation on a `while` loop is a "do-while loop." ```java +~void main() { int x = 0; do { System.out.println(x); - x++ + x++; } while(x < 5); +~} ``` You write `do`, some code inside of `{` and `}`, and then `while`, a condition inside of `(` and `)`, and finally a semicolon. -```java +```java,no_run do { } while (CONDITION); @@ -23,14 +25,16 @@ In most situations it works exactly the same as a regular while loop. The only d is that the first time the loop is reached the condition for the loop is not checked. ```java +~void main() { int x = 0; do { System.out.println("this will run"); -} while (x != 0) +} while (x != 0); while (x != 0) { System.out.println("this will not run"); } +~} ``` One way to remember the difference is that in a "do-while loop" you always "do the thing" diff --git a/src/loops/endless_loops.md b/src/loops/endless_loops.md index d8c0c10..94b7fad 100644 --- a/src/loops/endless_loops.md +++ b/src/loops/endless_loops.md @@ -4,20 +4,24 @@ If a while loop will never end, we call that an endless loop. This can happen if the condition is a constant like `while (true)` -```java +```java,no_run +~void main() { while (true) { System.out.println("This is the song that never ends"); } +~} ``` Or if the variables tested in the condition are not updated inside of the loop. -```java +```java,no_run +~void main() { // x is never changed int x = 0; while (x != 1) { System.out.println("It goes on and on my friends"); } +~} ``` Many games should never really "finish" so at the very start of that sort of program it is not uncommon diff --git a/src/loops/iterate_over_a_string.md b/src/loops/iterate_over_a_string.md index 57e5ed4..4aecc60 100644 --- a/src/loops/iterate_over_a_string.md +++ b/src/loops/iterate_over_a_string.md @@ -5,6 +5,7 @@ especially useful when you want to iterate over each character in a `String`. ```java +~void main() { String name = "Avril"; int index = 0; @@ -12,4 +13,5 @@ while (index < name.length()) { System.out.println(name.charAt(index)); index++; } +~} ``` diff --git a/src/loops/iteration.md b/src/loops/iteration.md index 95b7911..2f4ec38 100644 --- a/src/loops/iteration.md +++ b/src/loops/iteration.md @@ -4,6 +4,7 @@ Loops potentially run code multiple times. Each time one goes from its top to it we call that an "iteration" of the loop. ```java +~void main() { int x = 0; while (x < 5) { // On the 1st iteration x will be 0 @@ -13,6 +14,7 @@ while (x < 5) { System.out.println(x); x++ } +~} ``` When the purpose of a loop is to run for every thing in some sequence of things, diff --git a/src/loops/labeled_break.md b/src/loops/labeled_break.md index ac61352..8329ddb 100644 --- a/src/loops/labeled_break.md +++ b/src/loops/labeled_break.md @@ -3,25 +3,27 @@ If you want to break out of a nested loop from one of the inner loops, you can use a "labeled break." ```java +~void main() { outerLoop: while (true) { while (true) { break outerLoop; } } +~} ``` To do this, before your outer while or do-while loop you need to add a "label" followed by a `:`. A label is an arbitrary name just like a variable's name. -```java +```java,no_run