From 228a61e6325f85a7e75d62128aa51ae876895343 Mon Sep 17 00:00:00 2001 From: "Dr. Martin Goik" <goik@hdm-stuttgart.de> Date: Thu, 4 Oct 2018 19:18:26 +0200 Subject: [PATCH] qandaset and all figures linked to forum, exercise icon, cosmetics --- Doc/Sd1/arrays.xml | 292 ++-- Doc/Sd1/collections.xml | 150 +- Doc/Sd1/coreClasses.xml | 207 +-- Doc/Sd1/deployment.xml | 77 +- Doc/Sd1/errorHandling.xml | 32 +- Doc/Sd1/gettingStarted.xml | 40 +- Doc/Sd1/inheritance.xml | 304 ++-- Doc/Sd1/languageFundamentals.xml | 226 +-- Doc/Sd1/objectsClasses.xml | 1274 +++++++++-------- Doc/Sd1/statements.xml | 591 ++++---- Doc/Sd1/streams.xml | 126 +- Doc/Sda1/dom.xml | 866 +++++++---- .../webhelp/common/images/yoga-exercise.svg | 297 ++++ .../CustomLayer/webhelp/hdmextensions.xsl | 3 + .../CustomLayer/webhelp/positioning.css.patch | 2 +- ws/Docbook/Extensions/Tdata/Common/fig.xml | 14 - ws/Docbook/Preprocess/Xsl/docbook2html.xsl | 166 ++- 17 files changed, 2640 insertions(+), 2027 deletions(-) create mode 100644 ws/Docbook/CustomLayer/webhelp/common/images/yoga-exercise.svg diff --git a/Doc/Sd1/arrays.xml b/Doc/Sd1/arrays.xml index 9973f11cb..e88ad18ab 100644 --- a/Doc/Sd1/arrays.xml +++ b/Doc/Sd1/arrays.xml @@ -196,7 +196,7 @@ primes[4] = 11; "England" ,"France" ,"Germany" - };</programlisting> +};</programlisting> <para>An application is supposed to generate the following output:</para> @@ -327,34 +327,34 @@ primes[4] = 11; <para>A given route will be defined by an array of segments:</para> - <programlisting language="java"> final Segment[] route = new Segment[] { - new Segment(2.4, 50) - ,new Segment(5, 100) - ,new Segment(3.1, 50) - ,new Segment(0.8, 30) - };</programlisting> + <programlisting language="java">final Segment[] route = new Segment[] { + new Segment(2.4, 50) + ,new Segment(5, 100) + ,new Segment(3.1, 50) + ,new Segment(0.8, 30) +};</programlisting> <para>Implement a method <methodname>duration(...)</methodname> which allows for calculation the minimum expected time required with respect to speed limits along a given route.</para> - <programlisting language="java"> /** - * Minimal time required when consequently traveling with the minimum of - * official speed limits and the driver's personal maximum speed. If a - * leg does not have any speed limit the value of personalSpeedLimit will - * be used for calculation instead. - * - * @param route The array of segments composing a route. - * - * @param personalSpeedLimit The drivers personal speed limit whether or - * not official limits apply. Must be greater than 0. - * - * @return The minimal duration in (rounded) minutes with respect to all - * speed limits. Must be a positive (non-zero) value. - */ - static public long duration(Segment[] route, int personalSpeedLimit) { - return 0; // TODO - } + <programlisting language="java">/** + * Minimal time required when consequently traveling with the minimum of + * official speed limits and the driver's personal maximum speed. If a + * leg does not have any speed limit the value of personalSpeedLimit will + * be used for calculation instead. + * + * @param route The array of segments composing a route. + * + * @param personalSpeedLimit The drivers personal speed limit whether or + * not official limits apply. Must be greater than 0. + * + * @return The minimal duration in (rounded) minutes with respect to all + * speed limits. Must be a positive (non-zero) value. +*/ +static public long duration(Segment[] route, int personalSpeedLimit) { + return 0; // TODO +} </programlisting> <para>Write <xref linkend="glo_Junit"/> tests to cover different @@ -2117,32 +2117,33 @@ x..</screen></td> <programlisting language="java">public enum Player { - PLAYER1("Jim", 'O'), PLAYER2("Eve", 'X'); + PLAYER1("Jim", 'O'), PLAYER2("Eve", 'X'); - public final String nickname; - public final char representation; + public final String nickname; + public final char representation; - Player(final String nickname, final char representation) { - this.nickname = nickname; - this.representation = representation; - } + Player(final String nickname, final char representation) { + this.nickname = nickname; + this.representation = representation; + } - public Player getOtherPlayer() { - switch (this) { - case PLAYER1: - return PLAYER2; - case PLAYER2: - return PLAYER1; - default: + public Player getOtherPlayer() { + switch (this) { + case PLAYER1: + return PLAYER2; + case PLAYER2: + return PLAYER1; + + default: return null; - } - } + } + } - @Override - public String toString() { - return "" + representation; - } - }</programlisting> + @Override + public String toString() { + return "" + representation; + } +}</programlisting> <para>A <xref linkend="glo_Java"/> <code language="java">enum</code> essentially is a specialized class. @@ -2151,53 +2152,53 @@ x..</screen></td> <programlisting language="java">public class Player { - final public static Player - PLAYER1 = new Player ("Jim", 'O'), - PLAYER2 = new Player("Eve", 'X'); + final public static Player + PLAYER1 = new Player ("Jim", 'O'), + PLAYER2 = new Player("Eve", 'X'); - public final String nickname; - public final char representation; + public final String nickname; + public final char representation; - Player(final String nickname, final char representation) { - this.nickname = nickname; - this.representation = representation; - } + Player(final String nickname, final char representation) { + this.nickname = nickname; + this.representation = representation; + } - public Player getOtherPlayer() { + public Player getOtherPlayer() { - if (PLAYER1 == this) { - return PLAYER2; - } else if (PLAYER2 == this) { - return PLAYER1; - } else { - return null; - } + if (PLAYER1 == this) { + return PLAYER2; + } else if (PLAYER2 == this) { + return PLAYER1; + } else { + return null; } + } - @Override - public String toString() { - return "" + representation; - } - }</programlisting> + @Override + public String toString() { + return "" + representation; + } +}</programlisting> <para>It is possible to wrap this solution into an executable <xref linkend="glo_Jar"/> archive by adding:</para> - <programlisting language="xml"> <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <version>2.6</version> - <configuration> - <archive> - <manifest> - <addClasspath>true</addClasspath> - <!-- Class containing desired entry method public - static void main(String[] args) --> - <mainClass>de.hdm_stuttgart.mi.sd1.tictactoe.TicTacToe</mainClass> - </manifest> - </archive> - </configuration> - </plugin></programlisting> + <programlisting language="xml"><plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <version>2.6</version> + <configuration> + <archive> + <manifest> + <addClasspath>true</addClasspath> + <!-- Class containing desired entry method public + static void main(String[] args) --> + <mainClass>de.hdm_stuttgart.mi.sd1.tictactoe.TicTacToe</mainClass> + </manifest> + </archive> + </configuration> +</plugin></programlisting> <para>This allows for console execution rather than using your <xref linkend="glo_IDE"/>:</para> @@ -2532,23 +2533,22 @@ public void testApp() { given <code language="java">long</code> number is prime or not:</para> - <programlisting language="java"> /** - * Test, whether a given number is prime. - * @param candidate The number to be assessed - * @return true if candidate is prime, false otherwise - * <dl> - <dt>Precondition:</dt> - <dd>2 &lt;= candidate</dd> - </dl> - */ - public static boolean isPrime(final long candidate) { - for (long i = 2; i * i < candidate; i++) { // Just test up to square - if (0 == candidate % i) { // root of candidate. - return false; - } + <programlisting language="java">/** + * Test, whether a given number is prime. + * @param candidate The number to be assessed + * @return true if candidate is prime, false otherwise + * <dl> + * <dt>Precondition:</dt> + * <dd>2 &lt;= candidate</dd> + * </dl> + **/ +public static boolean isPrime(final long candidate) { + for (long i = 2; i * i < candidate; i++) { // Just test up to square + if (0 == candidate % i) { // root of candidate. + return false; } - return true; } + return true; }</programlisting> <orderedlist> @@ -2634,9 +2634,9 @@ public void testApp() { is due to the chosen limit <code language="java">i * i < candidate</code> in:</para> - <programlisting language="java"> public static boolean isPrime(final long candidate) { - for (long i = 2; i * i < candidate; i++) { - ...</programlisting> + <programlisting language="java">public static boolean isPrime(final long candidate) { + for (long i = 2; i * i < candidate; i++) { + ...</programlisting> <para>This is wrong: Having <code language="java">candidate == 49</code> the last value of i to be considered will be 6. @@ -2646,9 +2646,9 @@ public void testApp() { language="java">i * i <emphasis role="red"><=</emphasis> candidate</code> instead:</para> - <programlisting language="none"> public static boolean isPrime(final long candidate) { - for (long i = 2; i * i <emphasis role="bold"><emphasis role="red"><=</emphasis></emphasis> candidate; i++) { - ...</programlisting> + <programlisting language="none">public static boolean isPrime(final long candidate) { + for (long i = 2; i * i <emphasis role="bold"><emphasis role="red"><=</emphasis></emphasis> candidate; i++) { + ...</programlisting> <para>This way <code language="java">49 % 7</code> will be evaluated to zero thus returning <code @@ -2791,13 +2791,13 @@ public void testApp() { provide an additional method returning the array of values being added so far:</para> - <programlisting language="java"> /** - * @return The array of values entered so far - */ - public int[] getValues() { + <programlisting language="java">/** + * @return The array of values entered so far + */ +public int[] getValues() { ... - return ...; - }</programlisting> + return ...; +}</programlisting> <caution> <para>Do not just return your internal array <code @@ -2931,18 +2931,18 @@ values newArray | 1| 2| F| 7| 9| | ...</screen> one element in order to be able returning a meaningful result:</para> - <programlisting language="java"> /** - *<dl> - <dt><b>Precondition:</b></dt> - <dd>There must be at least one element.</dd> - </dl> - * - * @return The sample's median. - */ - public double getMedian() { + <programlisting language="java">/** + * <dl> + * <dt><b>Precondition:</b></dt> + * <dd>There must be at least one element.</dd> + * </dl> + * + * @return The sample's median. + */ +public double getMedian() { ... - return ... ; - }</programlisting> + return ... ; +}</programlisting> </listitem> <listitem> @@ -3082,9 +3082,9 @@ values newArray | 1| 2| F| 7| 9| | ...</screen> method thus adding each array value one by one. Consider an alternative naive implementation:</para> - <programlisting language="java"> public IntegerStore(final int[] values) { - this.values = values; - }</programlisting> + <programlisting language="java">public IntegerStore(final int[] values) { + this.values = values; +}</programlisting> <para>This will fail in most cases since the array parameter typically contains unsorted values.</para> @@ -3093,11 +3093,11 @@ values newArray | 1| 2| F| 7| 9| | ...</screen> tests:</para> <programlisting language="java">... - @Test - public void testMedian() { - IntegerStore store = new IntegerStore(new int[] {2, 7, 0, -3, 4}); - assertArrayEquals(new int[] {-3, 0, 2, 4, 7}, store.getValues()); - assertTrue(Math.abs(2. - store.getMedian()) < 1.E-10); +@Test +public void testMedian() { + IntegerStore store = new IntegerStore(new int[] {2, 7, 0, -3, 4}); + assertArrayEquals(new int[] {-3, 0, 2, 4, 7}, store.getValues()); + assertTrue(Math.abs(2. - store.getMedian()) < 1.E-10); ...</programlisting> </listitem> @@ -3106,24 +3106,24 @@ values newArray | 1| 2| F| 7| 9| | ...</screen> </listitem> <listitem> - <programlisting language="java"> @Test - public void testMedian() { - IntegerStore store = new IntegerStore(new int[] {2, 7, 0, -3, 4}); - assertArrayEquals(new int[] {-3, 0, 2, 4, 7}, store.getValues()); - assertTrue(Math.abs(2. - store.getMedian()) < 1.E-10); - - store.addValue(7); - assertArrayEquals(new int[] {-3, 0, 2, 4, 7, 7}, store.getValues()); - assertTrue(Math.abs(3. - store.getMedian()) < 1.E-10); - - store.addValue(7); - assertArrayEquals(new int[] {-3, 0, 2, 4, 7, 7, 7}, store.getValues()); - assertTrue(Math.abs(4. - store.getMedian()) < 1.E-50); - - store.addValue(6); - assertArrayEquals(new int[] {-3, 0, 2, 4, 6, 7, 7, 7}, store.getValues()); - assertTrue(Math.abs(5. - store.getMedian()) < 1.E-50); - }</programlisting> + <programlisting language="java">@Test +public void testMedian() { + IntegerStore store = new IntegerStore(new int[] {2, 7, 0, -3, 4}); + assertArrayEquals(new int[] {-3, 0, 2, 4, 7}, store.getValues()); + assertTrue(Math.abs(2. - store.getMedian()) < 1.E-10); + + store.addValue(7); + assertArrayEquals(new int[] {-3, 0, 2, 4, 7, 7}, store.getValues()); + assertTrue(Math.abs(3. - store.getMedian()) < 1.E-10); + + store.addValue(7); + assertArrayEquals(new int[] {-3, 0, 2, 4, 7, 7, 7}, store.getValues()); + assertTrue(Math.abs(4. - store.getMedian()) < 1.E-50); + + store.addValue(6); + assertArrayEquals(new int[] {-3, 0, 2, 4, 6, 7, 7, 7}, store.getValues()); + assertTrue(Math.abs(5. - store.getMedian()) < 1.E-50); +}</programlisting> </listitem> <listitem> diff --git a/Doc/Sd1/collections.xml b/Doc/Sd1/collections.xml index b0f604c42..bc45fbc84 100644 --- a/Doc/Sd1/collections.xml +++ b/Doc/Sd1/collections.xml @@ -102,14 +102,14 @@ and write each value to <code language="java">System.out</code>:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final Set<String> names = new HashSet<String>(); - names.add(... + final Set<String> names = new HashSet<String>(); + names.add(... ... - // Iterate over all inserted coordinates - for (... - }</programlisting> + // Iterate over all inserted coordinates + for (... +}</programlisting> </question> <answer> @@ -117,21 +117,21 @@ for-each loop allows iterating over the set to write its content to standard output:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final Set<String> names = new HashSet<String>(); + final Set<String> names = new HashSet<String>(); - names.add("Eve"); - names.add("Jim"); - names.add("Tom"); - names.add("Jim"); + names.add("Eve"); + names.add("Jim"); + names.add("Tom"); + names.add("Jim"); - // Iterate over all inserted coordinates - System.out.println("The set contains " + names.size() + " elements:"); - for (final String s : names) { - System.out.println(s); - } - }</programlisting> + // Iterate over all inserted coordinates + System.out.println("The set contains " + names.size() + " elements:"); + for (final String s : names) { + System.out.println(s); + } +}</programlisting> <para>Notice the duplicate name <code language="java">"Jim"</code>: Since our collection does have set @@ -166,40 +166,40 @@ Eve</screen> and write each value to <code language="java">System.out</code>:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final List<String> names = ...; + final List<String> names = ...; - names.add(... + names.add(... ... - // Iterate over all inserted strings - System.out.println("The list contains " + names.size() + " elements:"); - for (final String s : names) { - System.out.println(s); - } - }</programlisting> + // Iterate over all inserted strings + System.out.println("The list contains " + names.size() + " elements:"); + for (final String s : names) { + System.out.println(s); + } +}</programlisting> </question> <answer> <para>Our code closely resembles <xref linkend="sd1QandaSetString"/>:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final List<String> names = new Vector<String>(); + final List<String> names = new Vector<String>(); - names.add("Eve"); - names.add("Jim"); - names.add("Tom"); - names.add("Jim"); + names.add("Eve"); + names.add("Jim"); + names.add("Tom"); + names.add("Jim"); - // Iterate over all inserted strings - System.out.println("The list contains " + names.size() + " elements:"); - for (final String s : names) { - System.out.println(s); - } - }</programlisting> + // Iterate over all inserted strings + System.out.println("The list contains " + names.size() + " elements:"); + for (final String s : names) { + System.out.println(s); + } +}</programlisting> <para>This time the duplicate actually shows up:</para> @@ -239,19 +239,19 @@ Jim</screen> xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals()</methodname> to allow execution of:</para> - <programlisting language="java"> // Defining and testing integer coordinates - final Coordinate - c12 = new Coordinate(1, 2), - c52 = new Coordinate(5, 0), - c12Duplicate = new Coordinate(1, 2); + <programlisting language="java">// Defining and testing integer coordinates +final Coordinate + c12 = new Coordinate(1, 2), + c52 = new Coordinate(5, 0), + c12Duplicate = new Coordinate(1, 2); - System.out.println("c12:"+ c12); - System.out.println("c12.equals(c52):"+ c12.equals(c52)); - System.out.println("c12.equals(c12Duplicate):"+ c12.equals(c12Duplicate)); - System.out.println("c12.equals(\"dummy\"):"+ c12.equals("dummy")); +System.out.println("c12:"+ c12); +System.out.println("c12.equals(c52):"+ c12.equals(c52)); +System.out.println("c12.equals(c12Duplicate):"+ c12.equals(c12Duplicate)); +System.out.println("c12.equals(\"dummy\"):"+ c12.equals("dummy")); - System.out.println(c12);</programlisting> +System.out.println(c12);</programlisting> <para>This should yield the expected output:</para> @@ -330,17 +330,17 @@ c12.equals("dummy"):false <para>Our code is very similar to <xref linkend="sd1QandaSetString"/>:</para> - <programlisting language="java"> final Set<Coordinate> points = new HashSet<Coordinate>(); + <programlisting language="java">final Set<Coordinate> points = new HashSet<Coordinate>(); - points.add(new Coordinate(1, 2)); - points.add(new Coordinate(4, 1)); - points.add(new Coordinate(1, 2)); // Equal to first Object +points.add(new Coordinate(1, 2)); +points.add(new Coordinate(4, 1)); +points.add(new Coordinate(1, 2)); // Equal to first Object - // Iterate over all inserted coordinates - System.out.println("The set contains " + points.size() + " elements:"); - for (final Coordinate c : points) { - System.out.println(c.toString()); - }</programlisting> +// Iterate over all inserted coordinates +System.out.println("The set contains " + points.size() + " elements:"); +for (final Coordinate c : points) { + System.out.println(c.toString()); +}</programlisting> <para>Since we do have set semantics we expect the duplicate coordinate value <code>(1|2)</code> to be dropped and thus to @@ -359,12 +359,12 @@ c12.equals("dummy"):false xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals()</methodname> method. Consider:</para> - <programlisting language="java"> final Coordinate - c12 = new Coordinate(1, 2), - c12Duplicate = new Coordinate(1, 2); + <programlisting language="java">final Coordinate + c12 = new Coordinate(1, 2), + c12Duplicate = new Coordinate(1, 2); - System.out.println("c12.hashCode() and c12Duplicate.hashCode():"+ - c12.hashCode() + "," + c12Duplicate.hashCode());</programlisting> +System.out.println("c12.hashCode() and c12Duplicate.hashCode():"+ + c12.hashCode() + "," + c12Duplicate.hashCode());</programlisting> <para>This yields the following output:</para> @@ -525,18 +525,18 @@ c12.equals("dummy"):false <para>The input file smalltest.txt may be used to define a <xref linkend="glo_Junit"/> test:</para> - <programlisting language="java"> @Test - public void testWordSet() throws FileNotFoundException, IOException { + <programlisting language="java">@Test +public void testWordSet() throws FileNotFoundException, IOException { - final Set<String> expectedStrings = - new HashSet <String>(Arrays.asList(new String[]{ + final Set<String> expectedStrings = + new HashSet <String>(Arrays.asList(new String[]{ "A", "simple", "collection", "of", "words", "Some", "may", "appear", "multiple", "times" - })); + })); - final TextFileHandler tfh = new TextFileHandler("smalltest.txt"); - Assert.assertTrue(tfh.getWords().equals(expectedStrings)); - }</programlisting> + final TextFileHandler tfh = new TextFileHandler("smalltest.txt"); + Assert.assertTrue(tfh.getWords().equals(expectedStrings)); +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -566,10 +566,10 @@ c12.equals("dummy"):false by a <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/SortedSet.html">SortedSet</classname>:</para> - <programlisting language="java"> /** - * The set of words found so far. - */ - final SortedSet<String> words = new TreeSet<String>();</programlisting> + <programlisting language="java">/** + * The set of words found so far. + */ +final SortedSet<String> words = new TreeSet<String>();</programlisting> </answer> </qandaentry> </qandadiv> diff --git a/Doc/Sd1/coreClasses.xml b/Doc/Sd1/coreClasses.xml index 99d8e2f2d..8164ce7ad 100644 --- a/Doc/Sd1/coreClasses.xml +++ b/Doc/Sd1/coreClasses.xml @@ -269,12 +269,13 @@ equals: true</screen></td> linkend="sd1QandaSquareNumberTableFormatted"/> and other exercises. Consider the following snippet:</para> - <programlisting language="java"> int value = 33; - double secondValue = 114.317; + <programlisting language="java">int value = 33; +double secondValue = 114.317; - System.out.format("Just a single integer %3d\n", value); - System.out.format("An integer %3d and a double value %6.2f\n", - value, secondValue);</programlisting> +System.out.format("Just a single integer %3d\n", value); + +System.out.format("An integer %3d and a double value %6.2f\n", + value, secondValue);</programlisting> <para>Something seems to be odd here: The format() method is being called with a different number of arguments. Actually we may call @@ -328,11 +329,11 @@ equals: true</screen></td> <para>Consider the following snippet:</para> - <programlisting language="java"> final int v = 33; - final double d = 114.317; - final short color = 255; + <programlisting language="java">final int v = 33; +final double d = 114.317; +final short color = 255; - System.out.format("v=%d, d=%5.2f, color=%2x\n", v, d, color);</programlisting> +System.out.format("v=%d, d=%5.2f, color=%2x\n", v, d, color);</programlisting> <para>This generates the following output:</para> @@ -341,8 +342,8 @@ equals: true</screen></td> <para>We may prettify our code to better reflect the one to one correspondence between format strings and variables:</para> - <programlisting language="java"> System.out.format("v=%d, d=%5.2f, color=%2x\n", - v, d, color);</programlisting> + <programlisting language="java">System.out.format("v=%d, d=%5.2f, color=%2x\n", + v, d, color);</programlisting> <caution> <para>A failure in providing appropriate numbers of arguments @@ -386,12 +387,12 @@ java.util.IllegalFormatConversionException: <emphasis role="bold">d != java.lang <programlisting language="java">public static void main(String[] args) { - double radius = 2.31; // A circle having a radius (given e.g. in mm). - final double pi = 3.1415926; // Creating pi as a constant (non-modifiable/ - // assignable) variable. + double radius = 2.31; // A circle having a radius (given e.g. in mm). + final double pi = 3.1415926; // Creating pi as a constant (non-modifiable/ + // assignable) variable. - final double area = pi * radius * radius; - System.out.println(area); + final double area = pi * radius * radius; + System.out.println(area); }</programlisting> <para>You may have wondered why you had to punch in the value of @@ -418,10 +419,10 @@ java.util.IllegalFormatConversionException: <emphasis role="bold">d != java.lang <programlisting language="java" linenumbering="numbered">public static void main(String[] args) { - double radius = 2.31; // A circle having a radius (given e.g. in mm). + double radius = 2.31; // A circle having a radius (given e.g. in mm). - final double area = Math.PI * radius * radius; - System.out.println(area); + final double area = Math.PI * radius * radius; + System.out.println(area); }</programlisting> <para>In case you bother about using the somewhat clumsy <varname @@ -698,17 +699,16 @@ public class CircleAreaCalculator { <para>We need two nested loops creating the desired table by traversing the <xref linkend="glo_unicode"/> block:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final StringBuffer sb = new StringBuffer(); - for (int i = 0x1F600; i < 0x1F650; i += 0x10) { // 1F600, 1F610, ..., 1F640 - for (int j = 0; j < 0x10; j++) { // 0, 1, 2, ..., 15 - sb.appendCodePoint(i + j).append(' '); - } - sb.append("\n"); // line break - } - System.out.println(sb); - } + final StringBuffer sb = new StringBuffer(); + for (int i = 0x1F600; i < 0x1F650; i += 0x10) { // 1F600, 1F610, ..., 1F640 + for (int j = 0; j < 0x10; j++) { // 0, 1, 2, ..., 15 + sb.appendCodePoint(i + j).append(' '); + } + sb.append("\n"); // line break + } + System.out.println(sb); }</programlisting> </answer> </qandaentry> @@ -805,8 +805,8 @@ public class CircleAreaCalculator { substring(...)</methodname> allows for accessing the set of all substrings of 13 adjacent digits:</para> - <programlisting language="java"> public static void main(String[] args) { - final String + <programlisting language="java">public static void main(String[] args) { + final String input = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" @@ -827,13 +827,13 @@ public class CircleAreaCalculator { + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725"; - final int numOfDigits = 13; // The intended number of adjacent digits + final int numOfDigits = 13; // The intended number of adjacent digits - for (int i = 0; i < input.length() - numOfDigits + 1; i++) { - final String fourDigitWord = input.substring(i, i + numOfDigits); - System.out.println(fourDigitWord); - } - }</programlisting> + for (int i = 0; i < input.length() - numOfDigits + 1; i++) { + final String fourDigitWord = input.substring(i, i + numOfDigits); + System.out.println(fourDigitWord); + } +}</programlisting> <para>This creates the following output:</para> @@ -854,37 +854,38 @@ public class CircleAreaCalculator { character '4' equals its ASCII value which is just 52. Thus we need a translation like:</para> - <programlisting language="java"> private static int getDigitValue (final char digit) { - switch(digit) { - case '0': return 0; - case '1': return 1; - case '2': return 2; - case '3': return 3; - case '4': return 4; - case '5': return 5; - case '6': return 6; - case '7': return 7; - case '8': return 8; - case '9': return 9; - default: + <programlisting language="java">private static int getDigitValue (final char digit) { + switch(digit) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + + default: System.err.println("Character '" + digit + "' is no digit, exiting"); System.exit(1); return 0; - } - }</programlisting> + } +}</programlisting> <para>Next we must compute a given string's product of digits. Taking the first value <code>7316717653133</code> from above we are looking for 7 × 3 ×1 × 6 ×7 × 1 ×7 × 6 × 5 × 3 × 1 × 3 × 3 = 5000940. We define:</para> - <programlisting language="java"> private static int getDigitProduct(final String digitWord) { - int product = 1; - for (int i = 0; i < digitWord.length(); i++) { - product *= getDigitValue(digitWord.charAt(i)); - } - return product; - }</programlisting> + <programlisting language="java">private static int getDigitProduct(final String digitWord) { + int product = 1; + for (int i = 0; i < digitWord.length(); i++) { + product *= getDigitValue(digitWord.charAt(i)); + } + return product; +}</programlisting> <para>Unfortunately this method sometimes returns weird results: The argument <code language="java">"5397536978179"</code> for @@ -907,21 +908,21 @@ public class CircleAreaCalculator { from <code language="java">int</code> to <code language="java">long</code>:</para> - <programlisting language="java"> private static <emphasis + <programlisting language="java">private static <emphasis role="bold">long</emphasis> getDigitProduct(final String digitWord) { - <emphasis role="bold">long</emphasis> product = 1; - for (int i = 0; i < digitWord.length(); i++) { - product *= getDigitValue(digitWord.charAt(i)); - } - return product; - }</programlisting> +<emphasis role="bold"> long</emphasis> product = 1; + for (int i = 0; i < digitWord.length(); i++) { + product *= getDigitValue(digitWord.charAt(i)); + } + return product; +}</programlisting> <para>Assembling these pieces leaves us with the following <code language="java">main(...)</code> method:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final String + final String input = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" @@ -944,21 +945,21 @@ public class CircleAreaCalculator { + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725"; - final int numOfDigits = 13; // The intended number of adjacent digits - - long maximumDigitProduct = 0; - String maxDigitString = null; - for (int i = 0; i < input.length() - numOfDigits + 1; i++) { - final String digitWord = input.substring(i, i + numOfDigits); - final long productOfDigits = getDigitProduct(digitWord); - if (maximumDigitProduct < productOfDigits) { - maximumDigitProduct = productOfDigits; - maxDigitString = digitWord; - } - } - System.out.println("The substring '" + maxDigitString + - "' yields the largest product value " + getDigitProduct(maxDigitString) + "."); - }</programlisting> + final int numOfDigits = 13; // The intended number of adjacent digits + + long maximumDigitProduct = 0; + String maxDigitString = null; + for (int i = 0; i < input.length() - numOfDigits + 1; i++) { + final String digitWord = input.substring(i, i + numOfDigits); + final long productOfDigits = getDigitProduct(digitWord); + if (maximumDigitProduct < productOfDigits) { + maximumDigitProduct = productOfDigits; + maxDigitString = digitWord; + } + } + System.out.println("The substring '" + maxDigitString + + "' yields the largest product value " + getDigitProduct(maxDigitString) + "."); +}</programlisting> <para>The largest product of 13 successive digits stems from the substring <code>"5576689664895</code>" <coref @@ -1108,20 +1109,20 @@ b1.equals(b2): true</programlisting> <question> <para>Consider the following code snippet:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final String reference = "Anton"; + final String reference = "Anton"; - final String name = "An" + "ton"; + final String name = "An" + "ton"; - System.out.println("Content:" + name); + System.out.println("Content:" + name); - if (name == reference) { - System.out.println("Instances are equal"); - } else { - System.out.println("Instances are not equal"); - } - }</programlisting> + if (name == reference) { + System.out.println("Instances are equal"); + } else { + System.out.println("Instances are not equal"); + } +}</programlisting> <para>Execute the above code.</para> @@ -1129,21 +1130,21 @@ b1.equals(b2): true</programlisting> <varname>name</varname> <coref linkend="sd1CoNamedefByConcatMethod"/> is being defined:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final String reference = "Anton"; + final String reference = "Anton"; - <emphasis role="bold">final String name = "An".concat("ton");</emphasis> <co + <emphasis role="bold">final String name = "An".concat("ton");</emphasis> <co xml:id="sd1CoNamedefByConcatMethod"/> - System.out.println("Content:" + name); + System.out.println("Content:" + name); - if (name == reference) { - System.out.println("Instances are equal"); - } else { - System.out.println("Instances are not equal"); - } - }</programlisting> + if (name == reference) { + System.out.println("Instances are equal"); + } else { + System.out.println("Instances are not equal"); + } +}</programlisting> <para>Explain the results.</para> diff --git a/Doc/Sd1/deployment.xml b/Doc/Sd1/deployment.xml index d59234833..ce63f6421 100644 --- a/Doc/Sd1/deployment.xml +++ b/Doc/Sd1/deployment.xml @@ -30,7 +30,9 @@ <question> <para>The following Maven project contains a series of yet unimplemented methods and corresponding tests currently being - excluded by an <interfacename xlink:href="https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Disabled.html">@Disabled</interfacename> annotation:</para> + excluded by an <interfacename + xlink:href="https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Disabled.html">@Disabled</interfacename> + annotation:</para> <annotation role="make"> <para role="eclipse">Sd1/Array/arraycalcExercise</para> @@ -57,15 +59,15 @@ public class ArrayMethodTest { <para>This effectively requires extending the concept of swapping just two integer values within a block</para> - <programlisting language="java"> int a = 3, b = 5; + <programlisting language="java">int a = 3, b = 5; - // Other code ... +// Other code ... - {// Swap values of a and b - final int tmp = a; - a = b; - b = tmp; - }</programlisting> +{// Swap values of a and b + final int tmp = a; + a = b; + b = tmp; +}</programlisting> </glossdef> </glossentry> @@ -105,27 +107,30 @@ public class ArrayMethodTest { xlink:href="P/Sd1/Array/arraycalcExercise/target/site/apidocs/de/hdm_stuttgart/mi/sd1/store/Arraymethods.html#containsSameElements-int:A-int:A-">containsSameElements</link></glossterm> <glossdef> - <para>You may copy <code language="java">int[] b</code> array to a - <quote>shadow</quote> array and then subsequently erase all - elements of <code language="java">int[] a</code> from this copy. The method - <link + <para>You may copy <code language="java">int[] b</code> + array to a <quote>shadow</quote> array and then subsequently + erase all elements of <code language="java">int[] a</code> + from this copy. The method <link xlink:href="P/Sd1/Array/arraycalcExercise/target/site/apidocs/de/hdm_stuttgart/mi/sd1/store/Arraymethods.html#findIndex-int:A-int-">findIndex</link> is quite helpful.</para> - <para>Consider for example <code language="java">int[] bCopy = {1, 3, 4, 3, - 7}</code> containing 5 elements. Suppose our array - <code language="java">a</code> contains the value 3 which exists at index - position 1 in <code language="java">bCopy</code>. We may override the value + <para>Consider for example <code language="java">int[] bCopy + = {1, 3, 4, 3, 7}</code> containing 5 elements. Suppose our + array <code language="java">a</code> contains the value 3 + which exists at index position 1 in <code + language="java">bCopy</code>. We may override the value index position 1 by the last array value 7 and thereby keeping track of reducing the number of array elements to 4 like {1, 7, 4, 3}.</para> - <para>Off course the array <code language="java">bCopy</code> cannot shrink. - But we may introduce an integer variable to account for the - effective number of array elements still to be considered. - If and only if all elements from <code language="java">a</code> are - subsequently found within <code language="java">bCopy</code> the two arrays - <code language="java">a</code> and <code language="java">b</code> are equal.</para> + <para>Off course the array <code + language="java">bCopy</code> cannot shrink. But we may + introduce an integer variable to account for the effective + number of array elements still to be considered. If and only + if all elements from <code language="java">a</code> are + subsequently found within <code language="java">bCopy</code> + the two arrays <code language="java">a</code> and <code + language="java">b</code> are equal.</para> </glossdef> </glossentry> </glosslist> @@ -170,17 +175,18 @@ Your sample's median is: 6.0</screen> <listitem xml:id="sd1OlMedianCmdLineStep1"> <para>Using command line values means entering strings rather then e.g. integer values: In the current example the Java - runtime will pass an array of strings <code language="java">{"2", "6", - "7"}</code> on behalf of the user's input <quote><code language="java">2 6 - 7</code></quote> to your <code language="java">main(String [] args)</code> - method. These strings must be converted to integer values. - This may be achieved by means of <methodname + runtime will pass an array of strings <code + language="java">{"2", "6", "7"}</code> on behalf of the user's + input <quote><code language="java">2 6 7</code></quote> to + your <code language="java">main(String [] args)</code> method. + These strings must be converted to integer values. This may be + achieved by means of <methodname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#parseInt-java.lang.String-">parseInt(String)</methodname>.</para> - <para>Depending on inconsistent user input like - <quote><code language="java">three</code></quote> instead of - <quote><code language="java">3</code></quote> you may decide to terminate your - application thereby providing a meaningful error + <para>Depending on inconsistent user input like <quote><code + language="java">three</code></quote> instead of <quote><code + language="java">3</code></quote> you may decide to terminate + your application thereby providing a meaningful error message:</para> <screen>goik >java -jar statistics-1.0.jar 1 2 three @@ -260,12 +266,13 @@ public class InputValidator { public InputValidator(final String[] userInput) {...} }</programlisting> - <para>You may then create an instance by supplying your - <code language="java">main(String[] args)</code> command line values:</para> + <para>You may then create an instance by supplying your <code + language="java">main(String[] args)</code> command line + values:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final InputValidator userInput = new InputValidator(args); + final InputValidator userInput = new InputValidator(args); ...</programlisting> <para>Choose your implementation with testing in mind.</para> diff --git a/Doc/Sd1/errorHandling.xml b/Doc/Sd1/errorHandling.xml index e595929e2..d5509799d 100644 --- a/Doc/Sd1/errorHandling.xml +++ b/Doc/Sd1/errorHandling.xml @@ -536,23 +536,23 @@ static public String convert(final String input) { <figure xml:id="sd1_errorHandling_fig_cardinalThrowErrorStep3"> <title>Step 3: Throwing <classname>CardinalException</classname></title> - <programlisting language="java"> /** - * Translate {"one", "two", "three"} to {"first", "second", "third"} - * @param input The input String to be translated. - * @return See above explanation. - * @throws CardinalException If input not from list. - */ - static public String convert(final String input) - throws CardinalException { - - switch (input) { - case "one": return "first"; - case "two": return "second"; - case "three": return "third"; - } - throw new CardinalException( + <programlisting language="java">/** + * Translate {"one", "two", "three"} to {"first", "second", "third"} + * @param input The input String to be translated. + * @return See above explanation. + * @throws CardinalException If input not from list. + */ +static public String convert(final String input) + throws CardinalException { + + switch (input) { + case "one": return "first"; + case "two": return "second"; + case "three": return "third"; + } + throw new CardinalException( "Sorry, no translation for '" + input + "' on offer"); - }</programlisting> +}</programlisting> </figure> <figure xml:id="sd1_errorHandling_fig_cardinalThrowErrorStep4"> diff --git a/Doc/Sd1/gettingStarted.xml b/Doc/Sd1/gettingStarted.xml index f2281e6a9..0aa0fc9e0 100644 --- a/Doc/Sd1/gettingStarted.xml +++ b/Doc/Sd1/gettingStarted.xml @@ -1940,19 +1940,19 @@ Binary files HelloWorld.class.1 and HelloWorld.class.2 differ</screen> <question> <para>Execute:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int a = 3, - b = 87; + int a = 3, + b = 87; - if (a < b) { - System.out.println("a is smaller than b"); - } else if (b < a) { - System.out.println("b is smaller than a"); - } else { - System.out.println("b equals a"); - } - }</programlisting> + if (a < b) { + System.out.println("a is smaller than b"); + } else if (b < a) { + System.out.println("b is smaller than a"); + } else { + System.out.println("b equals a"); + } +}</programlisting> <para>Test different values for <code language="java">a</code> and <code language="java">b</code> reaching all three @@ -1970,16 +1970,16 @@ Binary files HelloWorld.class.1 and HelloWorld.class.2 differ</screen> <qandadiv> <qandaentry> <question> - <para>Execute:</para> + <para>Execute</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int i = 0; - while ( i < 5) { - System.out.println("loop # " + i); - i = i + 1; - } - }</programlisting> + int i = 0; + while ( i < 5) { + System.out.println("loop # " + i); + i = i + 1; + } +}</programlisting> <para>Examine the result and implement the following modifications:</para> @@ -2711,7 +2711,7 @@ Generating /ma/goik/First/target/site/apidocs/help-doc.html... <itemizedlist> <listitem> <para><property>archetypeArtifactId</property>: - <option>mi-maven-archetype-quickstart</option> </para> + <option>mi-maven-archetype-quickstart</option></para> </listitem> <listitem> diff --git a/Doc/Sd1/inheritance.xml b/Doc/Sd1/inheritance.xml index 3f49aa771..22f897d61 100644 --- a/Doc/Sd1/inheritance.xml +++ b/Doc/Sd1/inheritance.xml @@ -70,40 +70,40 @@ }</programlisting></td> </tr> </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sda_inherit_fig_DuplicateCode-1-co" - xml:id="sda_inherit_fig_DuplicateCode-1"> - <para>The center coordinate (<code language="java">x</code>|<code - language="java">y)</code> appears both in - <classname>Rectangle</classname> and - <classname>Circle</classname>.</para> - </callout> - - <callout arearefs="sda_inherit_fig_DuplicateCode-2-co" - xml:id="sda_inherit_fig_DuplicateCode-2"> - <para>The move(...) method is being defined <emphasis - role="bold">identically</emphasis> both in - <classname>Rectangle</classname> and - <classname>Circle</classname>!</para> - </callout> - - <callout arearefs="sda_inherit_fig_DuplicateCode-3-co" - xml:id="sda_inherit_fig_DuplicateCode-3"> - <itemizedlist> - <listitem> - <para><property>width</property> and <property>height</property> - only appear in class <classname>Rectangle</classname>.</para> - </listitem> - <listitem> - <para><property>radius</property> only appears in class - Circle.</para> - </listitem> - </itemizedlist> - </callout> - </calloutlist> - </figure> + <calloutlist role="slideExclude"> + <callout arearefs="sda_inherit_fig_DuplicateCode-1-co" + xml:id="sda_inherit_fig_DuplicateCode-1"> + <para>The center coordinate (<code language="java">x</code>|<code + language="java">y)</code> appears both in + <classname>Rectangle</classname> and + <classname>Circle</classname>.</para> + </callout> + + <callout arearefs="sda_inherit_fig_DuplicateCode-2-co" + xml:id="sda_inherit_fig_DuplicateCode-2"> + <para>The move(...) method is being defined <emphasis + role="bold">identically</emphasis> both in + <classname>Rectangle</classname> and + <classname>Circle</classname>!</para> + </callout> + + <callout arearefs="sda_inherit_fig_DuplicateCode-3-co" + xml:id="sda_inherit_fig_DuplicateCode-3"> + <itemizedlist> + <listitem> + <para><property>width</property> and <property>height</property> + only appear in class <classname>Rectangle</classname>.</para> + </listitem> + <listitem> + <para><property>radius</property> only appears in class + Circle.</para> + </listitem> + </itemizedlist> + </callout> + </calloutlist> + </figure> <figure xml:id="sda_inherit_fig_ideaFactorOutCommonCode"> <title>Idea: Centralize common code</title> @@ -312,10 +312,10 @@ public Shape(double x,double y) { <figure xml:id="sda_inherit_fig_createRectangle"> <title>Creating <classname>Rectangle</classname> instances</title> - <programlisting language="java">final Rectangle r = new Rectangle(x, y <co - linkends="sda_inherit_fig_createRectangle-1" + <programlisting language="java">final Rectangle r = + new Rectangle(x, y <co linkends="sda_inherit_fig_createRectangle-1" xml:id="sda_inherit_fig_createRectangle-1-co"/>, - width, height <co + width, height <co linkends="sda_inherit_fig_createRectangle-2" xml:id="sda_inherit_fig_createRectangle-2-co"/>);</programlisting> @@ -354,23 +354,24 @@ public Rectangle(double x, double y, linkends="sda_inherit_fig_RectangleConstructor-2" xml:id="sda_inherit_fig_RectangleConstructor-2-co"/>; }</programlisting> - <calloutlist role="slideExclude"> - <callout arearefs="sda_inherit_fig_RectangleConstructor-1-co" - xml:id="sda_inherit_fig_RectangleConstructor-1"> - <para>Passing center coordinate to superclass constructor.</para> - <note> - <para>This must be the first statement.</para> - </note> - </callout> + <calloutlist role="slideExclude"> + <callout arearefs="sda_inherit_fig_RectangleConstructor-1-co" + xml:id="sda_inherit_fig_RectangleConstructor-1"> + <para>Passing center coordinate to superclass constructor.</para> - <callout arearefs="sda_inherit_fig_RectangleConstructor-2-co" - xml:id="sda_inherit_fig_RectangleConstructor-2"> - <para>Processing <code language="java">width</code> and <code - language="java">height</code> in <quote>current</quote> - subclass.</para> - </callout> - </calloutlist> + <note> + <para>This must be the first statement.</para> + </note> + </callout> + + <callout arearefs="sda_inherit_fig_RectangleConstructor-2-co" + xml:id="sda_inherit_fig_RectangleConstructor-2"> + <para>Processing <code language="java">width</code> and <code + language="java">height</code> in <quote>current</quote> + subclass.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sda_inherit_fig_RectangleLogging"> @@ -571,34 +572,35 @@ for (final Shape s : shapes) { <screen>Circle at (1.0|1.0), radius= 2.0: <emphasis role="red">area = 12.566370614359172</emphasis> Rectangle at (1.0|-1.0), width= 2.0, height=3.0: <emphasis role="red">area = 6.0</emphasis></screen> - <calloutlist role="slideExclude"> - <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-1-co" - xml:id="sda_inherit_fig_shapePolymorphicAreaCall-1"> - <para>An array of <classname>Shape</classname> references.</para> - </callout> - <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-2-co" - xml:id="sda_inherit_fig_shapePolymorphicAreaCall-2"> - <para>A <classname>Rectangle</classname> <quote>is a</quote> - <classname>Shape</classname> and likewise is - <classname>Circle</classname>. We can thus assign both - <classname>Circle</classname> and <classname>Rectangle</classname> - instances to variables (or array elements) of type - <classname>Shape</classname> by means of upcasting.</para> - </callout> + <calloutlist role="slideExclude"> + <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-1-co" + xml:id="sda_inherit_fig_shapePolymorphicAreaCall-1"> + <para>An array of <classname>Shape</classname> references.</para> + </callout> - <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-3-co" - xml:id="sda_inherit_fig_shapePolymorphicAreaCall-3"> - <para>Polymorphic dispatch: Depending on the object's type the <xref - linkend="glo_Java"/> runtime will automatically choose either - <classname>Rectangle</classname>.<methodname>toString()</methodname>/ - <classname>Rectangle</classname>.<methodname>getArea()</methodname> or - <classname>Circle</classname>.<methodname>getArea()</methodname> / - <classname>Circle</classname>.<methodname>toString()</methodname>/ - <classname>Circle</classname>.<methodname>getArea()</methodname> - respectively.</para> - </callout> - </calloutlist> + <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-2-co" + xml:id="sda_inherit_fig_shapePolymorphicAreaCall-2"> + <para>A <classname>Rectangle</classname> <quote>is a</quote> + <classname>Shape</classname> and likewise is + <classname>Circle</classname>. We can thus assign both + <classname>Circle</classname> and <classname>Rectangle</classname> + instances to variables (or array elements) of type + <classname>Shape</classname> by means of upcasting.</para> + </callout> + + <callout arearefs="sda_inherit_fig_shapePolymorphicAreaCall-3-co" + xml:id="sda_inherit_fig_shapePolymorphicAreaCall-3"> + <para>Polymorphic dispatch: Depending on the object's type the <xref + linkend="glo_Java"/> runtime will automatically choose either + <classname>Rectangle</classname>.<methodname>toString()</methodname>/ + <classname>Rectangle</classname>.<methodname>getArea()</methodname> + or <classname>Circle</classname>.<methodname>getArea()</methodname> + / <classname>Circle</classname>.<methodname>toString()</methodname>/ + <classname>Circle</classname>.<methodname>getArea()</methodname> + respectively.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sda_inherit_fig_getAreaPolymorphicProblem"> @@ -667,50 +669,51 @@ Rectangle at (1.0|-1.0), width= 2.0, height=3.0: <emphasis role="red">area = 6.0 } ...</programlisting></td> </tr> </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sda_inherit_fig_implementAbstractGetArea-1-co" - xml:id="sda_inherit_fig_implementAbstractGetArea-1"> - <para>Superclass <classname>Shape</classname> contains an <code - language="java">abstract</code> method and must thus itself be - declared <code language="java">abstract</code> as well.</para> - - <note> - <para>You cannot create instances of <code - language="java">abstract</code> classes. You may however create - instances of derived non-<code language="java">abstract</code> - classes.</para> - </note> - </callout> - <callout arearefs="sda_inherit_fig_implementAbstractGetArea-2-co" - xml:id="sda_inherit_fig_implementAbstractGetArea-2"> - <para>Method <classname>getArea()</classname> cannot be implemented in - a meaningful way. Its <code language="java">abstract</code> modifier - is a promise that some concrete (= non-<code - language="java">abstract</code>) subclass will either offer an - implementation of <classname>getArea()</classname> or will have an - intermediate parent class doing so.</para> - - <para>In other words: The <code language="java">abstract</code> - keyword requires a corresponding implementation in some derived - non-<code language="java">abstract</code> subclass.</para> - </callout> + <calloutlist role="slideExclude"> + <callout arearefs="sda_inherit_fig_implementAbstractGetArea-1-co" + xml:id="sda_inherit_fig_implementAbstractGetArea-1"> + <para>Superclass <classname>Shape</classname> contains an <code + language="java">abstract</code> method and must thus itself be + declared <code language="java">abstract</code> as well.</para> + + <note> + <para>You cannot create instances of <code + language="java">abstract</code> classes. You may however create + instances of derived non-<code language="java">abstract</code> + classes.</para> + </note> + </callout> - <callout arearefs="sda_inherit_fig_implementAbstractGetArea-3-co" - xml:id="sda_inherit_fig_implementAbstractGetArea-3"> - <para>An <code language="java">abstract</code> method must not have an - implementing body <code language="java">{...}</code>.</para> - </callout> + <callout arearefs="sda_inherit_fig_implementAbstractGetArea-2-co" + xml:id="sda_inherit_fig_implementAbstractGetArea-2"> + <para>Method <classname>getArea()</classname> cannot be implemented + in a meaningful way. Its <code language="java">abstract</code> + modifier is a promise that some concrete (= non-<code + language="java">abstract</code>) subclass will either offer an + implementation of <classname>getArea()</classname> or will have an + intermediate parent class doing so.</para> + + <para>In other words: The <code language="java">abstract</code> + keyword requires a corresponding implementation in some derived + non-<code language="java">abstract</code> subclass.</para> + </callout> - <callout arearefs="sda_inherit_fig_implementAbstractGetArea-4-co" - xml:id="sda_inherit_fig_implementAbstractGetArea-4"> - <para>Both <classname>Rectangle</classname> and - <classname>Circle</classname> are concrete (=non-<code - language="java">abstract</code>) classes and are thus obliged to - provide an implementation of <methodname>double - getArea()</methodname>.</para> - </callout> - </calloutlist> + <callout arearefs="sda_inherit_fig_implementAbstractGetArea-3-co" + xml:id="sda_inherit_fig_implementAbstractGetArea-3"> + <para>An <code language="java">abstract</code> method must not have + an implementing body <code language="java">{...}</code>.</para> + </callout> + + <callout arearefs="sda_inherit_fig_implementAbstractGetArea-4-co" + xml:id="sda_inherit_fig_implementAbstractGetArea-4"> + <para>Both <classname>Rectangle</classname> and + <classname>Circle</classname> are concrete (=non-<code + language="java">abstract</code>) classes and are thus obliged to + provide an implementation of <methodname>double + getArea()</methodname>.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sda_inherit_fig_shapeGetAreaAbstract"> @@ -908,11 +911,11 @@ double p = c.move(1, 5).move(-3, 7).getPrimeter();</programlisting> <classname>Shape</classname>:</para> <programlisting language="java">/** - * - * @param factor Scale the current shape by this value. - * @return The current object. - */ - public abstract Shape scale(double factor);</programlisting> + * + * @param factor Scale the current shape by this value. + * @return The current object. + */ +public abstract Shape scale(double factor);</programlisting> <para>This method has to be implemented in our two concrete classes <classname>Circle</classname> and @@ -949,11 +952,11 @@ double p = c.move(1, 5).move(-3, 7).getPrimeter();</programlisting> <question> <para>Consider:</para> - <programlisting language="java"> final Circle c = new Circle(-2, -1, 3.5); - final Rectangle r = new Rectangle(3, 1, 1.5, 4.4); + <programlisting language="java">final Circle c = new Circle(-2, -1, 3.5); +final Rectangle r = new Rectangle(3, 1, 1.5, 4.4); - System.out.println(c); - System.out.println(r);</programlisting> +System.out.println(c); +System.out.println(r);</programlisting> <para>This creates the following output:</para> @@ -1023,33 +1026,34 @@ public class Rectangle <co linkends="sda_inherit_fig_protectedCreationTime-3" return width * height; } ... }</programlisting> - <calloutlist role="slideExclude"> - <callout arearefs="sda_inherit_fig_protectedCreationTime-1-co" - xml:id="sda_inherit_fig_protectedCreationTime-1"> - <para>Defining superclass <classname>Shape</classname> in package - <code language="java">model</code>.</para> - </callout> - <callout arearefs="sda_inherit_fig_protectedCreationTime-2-co" - xml:id="sda_inherit_fig_protectedCreationTime-2"> - <para>Defining a <code language="java">protected</code> instance - attribute <property>creationTime</property> in superclass - <classname>Shape</classname>.</para> - </callout> + <calloutlist role="slideExclude"> + <callout arearefs="sda_inherit_fig_protectedCreationTime-1-co" + xml:id="sda_inherit_fig_protectedCreationTime-1"> + <para>Defining superclass <classname>Shape</classname> in package + <code language="java">model</code>.</para> + </callout> - <callout arearefs="sda_inherit_fig_protectedCreationTime-3-co" - xml:id="sda_inherit_fig_protectedCreationTime-3"> - <para>Deriving class <classname>Rectangle</classname> in different - package <code language="java">model.sub</code> from superclass <code - language="java">Shape</code>.</para> - </callout> + <callout arearefs="sda_inherit_fig_protectedCreationTime-2-co" + xml:id="sda_inherit_fig_protectedCreationTime-2"> + <para>Defining a <code language="java">protected</code> instance + attribute <property>creationTime</property> in superclass + <classname>Shape</classname>.</para> + </callout> - <callout arearefs="sda_inherit_fig_protectedCreationTime-4-co" - xml:id="sda_inherit_fig_protectedCreationTime-4"> - <para>Accessing superclass attribute <property>creationTime</property> - across package boundary.</para> - </callout> - </calloutlist> + <callout arearefs="sda_inherit_fig_protectedCreationTime-3-co" + xml:id="sda_inherit_fig_protectedCreationTime-3"> + <para>Deriving class <classname>Rectangle</classname> in different + package <code language="java">model.sub</code> from superclass <code + language="java">Shape</code>.</para> + </callout> + + <callout arearefs="sda_inherit_fig_protectedCreationTime-4-co" + xml:id="sda_inherit_fig_protectedCreationTime-4"> + <para>Accessing superclass attribute + <property>creationTime</property> across package boundary.</para> + </callout> + </calloutlist> </figure> <qandaset defaultlabel="qanda" xml:id="sd1_qanda_protectedPackagePrivate"> diff --git a/Doc/Sd1/languageFundamentals.xml b/Doc/Sd1/languageFundamentals.xml index 7d7cfa441..5b5848363 100644 --- a/Doc/Sd1/languageFundamentals.xml +++ b/Doc/Sd1/languageFundamentals.xml @@ -1721,14 +1721,14 @@ System.out.println("Result: " + i);</programlisting></td> xlink:href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.1-100-C">int</code>'s minimum and maximum possible value to standard output.</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int minumum = ... , //TODO: provide values by - maximum = ...; // binary int literals + int minumum = ... , //TODO: provide values by + maximum = ...; // binary int literals - System.out.println("Minimum:" + minumum); - System.out.println("Maximum:" + maximum); - }</programlisting> + System.out.println("Minimum:" + minumum); + System.out.println("Maximum:" + maximum); +}</programlisting> </question> <answer> @@ -1740,12 +1740,12 @@ System.out.println("Result: " + i);</programlisting></td> <programlisting language="java">public static void main(String[] args) { - int minumum = 0B10000000_00000000_00000000_00000000, - maximum = 0B01111111_11111111_11111111_11111111; + int minumum = 0B10000000_00000000_00000000_00000000, + maximum = 0B01111111_11111111_11111111_11111111; - System.out.println("Minimum int value:" + minumum); - System.out.println("Maximum int value:" + maximum); - }</programlisting> + System.out.println("Minimum int value:" + minumum); + System.out.println("Maximum int value:" + maximum); +}</programlisting> <para>BTW: The <xref linkend="glo_JDK"/> does provide maximum value, minimum value and related information for <code @@ -1767,11 +1767,11 @@ System.out.println("Result: " + i);</programlisting></td> xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html">Integer</classname> classes. You may want to execute:</para> - <programlisting language="java"> System.out.println("int minimum:" + Integer.MIN_VALUE); - System.out.println("int maximum:" + Integer.MAX_VALUE); + <programlisting language="java">System.out.println("int minimum:" + Integer.MIN_VALUE); +System.out.println("int maximum:" + Integer.MAX_VALUE); - System.out.println("int bytes:" + Integer.BYTES); - System.out.println("int size:" + Integer.SIZE);</programlisting> +System.out.println("int bytes:" + Integer.BYTES); +System.out.println("int size:" + Integer.SIZE);</programlisting> </answer> </qandaentry> </qandadiv> @@ -1935,7 +1935,7 @@ int a = 20, System.out.println(a + " + " + b + " + " + c + " = " + (a + b + c)); - }</programlisting> +}</programlisting> <para>This will run smoothly producing the expected output:</para> @@ -1945,14 +1945,14 @@ int a = 20, right aligning numbers thereby padding leading positions with zeros:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int a = 20, - b = 03, - <emphasis role="bold">c = 09; // Compiler error: The literal 09 of type int is out of range</emphasis> + int a = 20, + b = 03, + <emphasis role="bold">c = 09; // Compiler error: The literal 09 of type int is out of range</emphasis> - System.out.println(a + " + " + b + " + " + c + " = " + (a + b + c)); - }</programlisting> + System.out.println(a + " + " + b + " + " + c + " = " + (a + b + c)); +}</programlisting> <para>The above code does not compile due to a compiler error when defining variable <code language="java">c</code>.</para> @@ -2707,7 +2707,7 @@ System.out.println(intensity);</programlisting> + 128 + 32 + 4)); - }</programlisting> +}</programlisting> <para>This yields:</para> @@ -4945,15 +4945,15 @@ System.out.println("Difference: " + difference);</programlisting><screen>Differe <para>In Exercise <xref linkend="sw1QandaCircleArea"/> you calculated a given circle's area:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - double radius = 2.31; // A circle having a radius (given e.g. in mm). - double pi = 3.1415926; // Constant relating a circle's radius, perimeter + double radius = 2.31; // A circle having a radius (given e.g. in mm). + double pi = 3.1415926; // Constant relating a circle's radius, perimeter //and area. - double area = pi * radius * radius; - System.out.println(area); - }</programlisting> + double area = pi * radius * radius; + System.out.println(area); +}</programlisting> <para>Though there is nothing wrong with this approach it is error prone: In a similar program a careless programmer accidentally @@ -5247,31 +5247,31 @@ System.out.println("A circle of radius " + radius + " will cover an area of " + <para>Write an application converting temperature values being represented as degree centigrade to kelvin and Fahrenheit:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - double temperatureCelsius = 23.2; + double temperatureCelsius = 23.2; ... - System.out.println("Celsius: " + temperatureCelsius); - System.out.println("Kelvin: " + temperatureKelvin); - System.out.println("Fahrenheit: " + temperatureFahrenheit); - }</programlisting> + System.out.println("Celsius: " + temperatureCelsius); + System.out.println("Kelvin: " + temperatureKelvin); + System.out.println("Fahrenheit: " + temperatureFahrenheit); +}</programlisting> </question> <answer> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - double temperatureCelsius = 23.2; + double temperatureCelsius = 23.2; - double + double temperatureKelvin = temperatureCelsius + 273.15, temperatureFahrenheit = 9 * temperatureCelsius / 5 + 32; - System.out.println("Celsius: " + temperatureCelsius); - System.out.println("Kelvin: " + temperatureKelvin); - System.out.println("Fahrenheit: " + temperatureFahrenheit); - }</programlisting> + System.out.println("Celsius: " + temperatureCelsius); + System.out.println("Kelvin: " + temperatureKelvin); + System.out.println("Fahrenheit: " + temperatureFahrenheit); +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -5290,17 +5290,17 @@ System.out.println("A circle of radius " + radius + " will cover an area of " + <para>Write an application converting a (seconds, minutes ,hours) time specification to seconds:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int + final int seconds = 31, minutes = 16, hours = 4; - int timeInSeconds ... + int timeInSeconds ... - System.out.println("Time in seconds:" + timeInSeconds); - }</programlisting> + System.out.println("Time in seconds:" + timeInSeconds); +}</programlisting> <para>The expected output reads:</para> @@ -5312,16 +5312,16 @@ System.out.println("A circle of radius " + radius + " will cover an area of " + time specification in seconds to (seconds, minutes ,hours) as in:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int timeInSeconds = 15391; + final int timeInSeconds = 15391; ... - System.out.println("Hours:" + hours); - System.out.println("Minutes:" + minutes); - System.out.println("Seconds:" + seconds); - }</programlisting> + System.out.println("Hours:" + hours); + System.out.println("Minutes:" + minutes); + System.out.println("Seconds:" + seconds); +}</programlisting> <para>The expected output reads:</para> @@ -5343,34 +5343,34 @@ Seconds:31</screen> <listitem> <para>A straightforward solution reads:</para> - <para><programlisting language="java"> public static void main(String[] args) { + <para><programlisting language="java">public static void main(String[] args) { - final int - seconds = 31, - minutes = 16, - hours = 4; + final int + seconds = 31, + minutes = 16, + hours = 4; - final int timeInSeconds = seconds + 60 * (minutes + 60 * hours); + final int timeInSeconds = seconds + 60 * (minutes + 60 * hours); - System.out.println("Time in seconds:" + timeInSeconds); - }</programlisting></para> + System.out.println("Time in seconds:" + timeInSeconds); +}</programlisting></para> </listitem> <listitem> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int timeInSeconds = 15391; + final int timeInSeconds = 15391; - final int minutesRemaining = timeInSeconds / 60; - final int seconds = timeInSeconds % 60; + final int minutesRemaining = timeInSeconds / 60; + final int seconds = timeInSeconds % 60; - final int hours = minutesRemaining / 60; - final int minutes = minutesRemaining % 60; + final int hours = minutesRemaining / 60; + final int minutes = minutesRemaining % 60; - System.out.println("Hours:" + hours); - System.out.println("Minutes:" + minutes); - System.out.println("Seconds:" + seconds); - }</programlisting> + System.out.println("Hours:" + hours); + System.out.println("Minutes:" + minutes); + System.out.println("Seconds:" + seconds); +}</programlisting> </listitem> </orderedlist> </answer> @@ -5388,18 +5388,18 @@ Seconds:31</screen> an initial capital, a given annual interest rate and a duration of three years. Consider the following code fragment:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final double initialCapital = 223.12; - final double interestRate = 1.5; + final double initialCapital = 223.12; + final double interestRate = 1.5; - System.out.println("Initial capital:" + initialCapital); - System.out.println("Annual interest rate:" + interestRate); + System.out.println("Initial capital:" + initialCapital); + System.out.println("Annual interest rate:" + interestRate); - // TODO ... + // TODO ... - System.out.println("Capital after three years:" + ...); - }</programlisting> + System.out.println("Capital after three years:" + ...); +}</programlisting> <para>The expected output is:</para> @@ -5437,41 +5437,41 @@ Capital after three years:233.31175902999993</screen> <para>Since we have not yet introduced loops this multiplication has to be repeated three times:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final double initialCapital = 223.12; - final double interestRate = 1.5; + final double initialCapital = 223.12; + final double interestRate = 1.5; - System.out.println("Initial capital:" + initialCapital); - System.out.println("Annual interest rate:" + interestRate); + System.out.println("Initial capital:" + initialCapital); + System.out.println("Annual interest rate:" + interestRate); - final double factor = 1. + interestRate/100.; - double capitalAtThreeYears = initialCapital; + final double factor = 1. + interestRate/100.; + double capitalAtThreeYears = initialCapital; - capitalAtThreeYears *= factor; // Year 1 - capitalAtThreeYears *= factor; // Year 2 - capitalAtThreeYears *= factor; // Year 3 + capitalAtThreeYears *= factor; // Year 1 + capitalAtThreeYears *= factor; // Year 2 + capitalAtThreeYears *= factor; // Year 3 - System.out.println("Capital after three years:" + capitalAtThreeYears); - }</programlisting> + System.out.println("Capital after three years:" + capitalAtThreeYears); +}</programlisting> <para>We might as well use a single arithmetic expression to achieve the same result:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final double initialCapital = 223.12; - final double interestRate = 1.5; + final double initialCapital = 223.12; + final double interestRate = 1.5; - System.out.println("Initial capital:" + initialCapital); - System.out.println("Annual interest rate:" + interestRate); + System.out.println("Initial capital:" + initialCapital); + System.out.println("Annual interest rate:" + interestRate); - final double factor = 1. + interestRate/100.; - final double capitalAtThreeYears = + final double factor = 1. + interestRate/100.; + final double capitalAtThreeYears = initialCapital * factor * factor * factor; - System.out.println("Capital after three years:" + capitalAtThreeYears); - }</programlisting> + System.out.println("Capital after three years:" + capitalAtThreeYears); +}</programlisting> <para>In <xref linkend="sd1InterestCalculator"/> we will present a more elaborate solution based on loops and class methods.</para> @@ -5682,25 +5682,25 @@ System.out.println("e=" + e);</programlisting> <para>The rest is just obeying the <quote>due diligence</quote> rule set:</para> - <programlisting language="java"> int a = 3; - a++; //Incrementing a by 1 --> a==4 + <programlisting language="java">int a = 3; +a++; //Incrementing a by 1 --> a==4 - int b = a; // Assigning value of a --> b==4 +int b = a; // Assigning value of a --> b==4 - b--; // Decrementing b by 1 --> b==3 - --b; // Decrementing b by 1 --> b==2 +b--; // Decrementing b by 1 --> b==3 +--b; // Decrementing b by 1 --> b==2 - int c = b; // c == 2; +int c = b; // c == 2; - b = ++a; // Incrementing a by 1 -->a==5, then assigning to b --> b == 5 - int e = a++; // Assigning a to e --> e==5, then incrementing a --> a==6 +b = ++a; // Incrementing a by 1 -->a==5, then assigning to b --> b == 5 +int e = a++; // Assigning a to e --> e==5, then incrementing a --> a==6 - a *= b; // Multiplying a with b and assigning the result to a --> a==30 +a *= b; // Multiplying a with b and assigning the result to a --> a==30 - System.out.println("a=" + a); - System.out.println("b=" + b); - System.out.println("c=" + c); - System.out.println("e=" + e);</programlisting> +System.out.println("a=" + a); +System.out.println("b=" + b); +System.out.println("c=" + c); +System.out.println("e=" + e);</programlisting> </answer> </qandaentry> </qandadiv> diff --git a/Doc/Sd1/objectsClasses.xml b/Doc/Sd1/objectsClasses.xml index bc87ebafe..2980308da 100644 --- a/Doc/Sd1/objectsClasses.xml +++ b/Doc/Sd1/objectsClasses.xml @@ -326,43 +326,43 @@ public class Q {<lineannotation>Class def</lineannotation> </glossentry> </glosslist> - <informaltable role="slideExclude" border="0"> - <tr> - <th>Fully qualified class name</th> + <informaltable border="0" role="slideExclude"> + <tr> + <th>Fully qualified class name</th> - <th>Using <code language="java">import</code></th> - </tr> + <th>Using <code language="java">import</code></th> + </tr> - <tr> - <td valign="top"><calloutlist> - <callout arearefs="sd1_callout_importVsQualifying-1.2-co" - xml:id="sd1_callout_importVsQualifying-1.2"> - <para>Using the fully qualified class name for defining a - variable.</para> - </callout> + <tr> + <td valign="top"><calloutlist> + <callout arearefs="sd1_callout_importVsQualifying-1.2-co" + xml:id="sd1_callout_importVsQualifying-1.2"> + <para>Using the fully qualified class name for defining a + variable.</para> + </callout> - <callout arearefs="sd1_callout_importVsQualifying-2.2-co" - xml:id="sd1_callout_importVsQualifying-2.2"> - <para>Creating an instance by using the fully qualified class - name again.</para> - </callout> - </calloutlist></td> + <callout arearefs="sd1_callout_importVsQualifying-2.2-co" + xml:id="sd1_callout_importVsQualifying-2.2"> + <para>Creating an instance by using the fully qualified class + name again.</para> + </callout> + </calloutlist></td> - <td valign="top"><calloutlist> - <callout arearefs="sd1_callout_importVsQualifying-3.2-co" - xml:id="sd1_callout_importVsQualifying-3.2"> - <para>Importing the <classname>Scanner</classname> class - once.</para> - </callout> + <td valign="top"><calloutlist> + <callout arearefs="sd1_callout_importVsQualifying-3.2-co" + xml:id="sd1_callout_importVsQualifying-3.2"> + <para>Importing the <classname>Scanner</classname> class + once.</para> + </callout> - <callout arearefs="sd1_callout_importVsQualifying-4.2-co" - xml:id="sd1_callout_importVsQualifying-4.2"> - <para>Unqualified class use due to <code - language="java">import</code>.</para> - </callout> - </calloutlist></td> - </tr> - </informaltable> + <callout arearefs="sd1_callout_importVsQualifying-4.2-co" + xml:id="sd1_callout_importVsQualifying-4.2"> + <para>Unqualified class use due to <code + language="java">import</code>.</para> + </callout> + </calloutlist></td> + </tr> + </informaltable> </figure> <figure xml:id="sd1_fig_importByWildcard"> @@ -422,31 +422,31 @@ public class Q { } }</programlisting> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_fig_javaDotLangNoImportRequired-1.2-co" - xml:id="sd1_fig_javaDotLangNoImportRequired-1.2"> - <para>Classes belonging to the <package - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/package-summary.html">java.lang</package> - package are being imported automatically.</para> - </callout> - - <callout arearefs="sd1_fig_javaDotLangNoImportRequired-2.2-co" - xml:id="sd1_fig_javaDotLangNoImportRequired-2.2"> - <para>The <classname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html">Scanner</classname> - class belongs to the <package - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/package-summary.html">java.util</package> - package and must thus be imported.</para> - </callout> - - <callout arearefs="sd1_fig_javaDotLangNoImportRequired-3-co" - xml:id="sd1_fig_javaDotLangNoImportRequired-3"> - <para>Without the import <classname>java.util.Scanner</classname> - statement we need the fully qualified class name:</para> - - <programlisting language="java">java.util.Scanner s = new java.util.Scanner(System.in);</programlisting> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_fig_javaDotLangNoImportRequired-1.2-co" + xml:id="sd1_fig_javaDotLangNoImportRequired-1.2"> + <para>Classes belonging to the <package + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/package-summary.html">java.lang</package> + package are being imported automatically.</para> + </callout> + + <callout arearefs="sd1_fig_javaDotLangNoImportRequired-2.2-co" + xml:id="sd1_fig_javaDotLangNoImportRequired-2.2"> + <para>The <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html">Scanner</classname> + class belongs to the <package + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/package-summary.html">java.util</package> + package and must thus be imported.</para> + </callout> + + <callout arearefs="sd1_fig_javaDotLangNoImportRequired-3-co" + xml:id="sd1_fig_javaDotLangNoImportRequired-3"> + <para>Without the import <classname>java.util.Scanner</classname> + statement we need the fully qualified class name:</para> + + <programlisting language="java">java.util.Scanner s = new java.util.Scanner(System.in);</programlisting> + </callout> + </calloutlist> </figure> <figure xml:id="sd1_fig_package2directory"> @@ -632,64 +632,64 @@ height=44</screen></td> </tr> </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_callout_methodSyntax-1-co" - xml:id="sd1_callout_methodSyntax-1"> - <para>Optional <link - xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#accesscontrol-levels">access - control</link> modifier either of <code language="java">public</code>, - <code language="java">protected</code> or <code - language="java">private</code>.</para> - </callout> - - <callout arearefs="sd1_callout_methodSyntax-2-co" - xml:id="sd1_callout_methodSyntax-2"> - <para>The method's return type either of:</para> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_callout_methodSyntax-1-co" + xml:id="sd1_callout_methodSyntax-1"> + <para>Optional <link + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#accesscontrol-levels">access + control</link> modifier either of <code + language="java">public</code>, <code + language="java">protected</code> or <code + language="java">private</code>.</para> + </callout> - <glosslist> - <glossentry> - <glossterm><code language="java">void</code></glossterm> + <callout arearefs="sd1_callout_methodSyntax-2-co" + xml:id="sd1_callout_methodSyntax-2"> + <para>The method's return type either of:</para> - <glossdef> - <para>The method will not return a value on completion.</para> - </glossdef> - </glossentry> + <glosslist> + <glossentry> + <glossterm><code language="java">void</code></glossterm> - <glossentry> - <glossterm>A data type <abbrev>e.g.</abbrev> <code - language="java">int</code>, <code language="java">double</code>, - ...</glossterm> + <glossdef> + <para>The method will not return a value on completion.</para> + </glossdef> + </glossentry> - <glossdef> - <para>The method will return a value of the given type to its - caller.</para> - </glossdef> - </glossentry> - </glosslist> - </callout> + <glossentry> + <glossterm>A data type <abbrev>e.g.</abbrev> <code + language="java">int</code>, <code language="java">double</code>, + ...</glossterm> - <callout arearefs="sd1_callout_methodSyntax-3-co" - xml:id="sd1_callout_methodSyntax-3"> - <para>The method's name.</para> - </callout> + <glossdef> + <para>The method will return a value of the given type to its + caller.</para> + </glossdef> + </glossentry> + </glosslist> + </callout> - <callout arearefs="sd1_callout_methodSyntax-4-co" - xml:id="sd1_callout_methodSyntax-4"> - <para>Arguments being required for execution.</para> - </callout> + <callout arearefs="sd1_callout_methodSyntax-3-co" + xml:id="sd1_callout_methodSyntax-3"> + <para>The method's name.</para> + </callout> - <callout arearefs="sd1_callout_methodSyntax-5-co" - xml:id="sd1_callout_methodSyntax-5"> - <para>Start of method's body.</para> - </callout> + <callout arearefs="sd1_callout_methodSyntax-4-co" + xml:id="sd1_callout_methodSyntax-4"> + <para>Arguments being required for execution.</para> + </callout> - <callout arearefs="sd1_callout_methodSyntax-6-co" - xml:id="sd1_callout_methodSyntax-6"> - <para>The method's implementation.</para> - </callout> - </calloutlist> - </figure> + <callout arearefs="sd1_callout_methodSyntax-5-co" + xml:id="sd1_callout_methodSyntax-5"> + <para>Start of method's body.</para> + </callout> + <callout arearefs="sd1_callout_methodSyntax-6-co" + xml:id="sd1_callout_methodSyntax-6"> + <para>The method's implementation.</para> + </callout> + </calloutlist> + </figure> <figure xml:id="fig_rectangleGetPerimeter"> <title>A rectangle's perimeter</title> @@ -1055,20 +1055,20 @@ public class Circle { <para>Instances of this class shall be usable in the following fashion:</para> - <programlisting language="java"> public static void main(String[] args) { - final Circle c = new Circle(2.3); + <programlisting language="java">public static void main(String[] args) { + final Circle c = new Circle(2.3); - System.out.println("Radius:" + c.getRadius()); - System.out.println("Perimeter:" + c.getPerimeter()); - System.out.println("Area:" + c.getArea()); + System.out.println("Radius:" + c.getRadius()); + System.out.println("Perimeter:" + c.getPerimeter()); + System.out.println("Area:" + c.getArea()); - // Changing the circle's radius to a different value - c.setRadius(4.7); + // Changing the circle's radius to a different value + c.setRadius(4.7); - System.out.println("Radius:" + c.getRadius()); - System.out.println("Perimeter:" + c.getPerimeter()); - System.out.println("Area:" + c.getArea()); - }</programlisting> + System.out.println("Radius:" + c.getRadius()); + System.out.println("Perimeter:" + c.getPerimeter()); + System.out.println("Area:" + c.getArea()); +}</programlisting> <para>Hint: Obviously you'll have to define an instance variable within Circle to keep track of its current radius value. All @@ -1089,9 +1089,9 @@ public class Circle { <para>Next we implement our method to change a circle's radius:</para> - <programlisting language="java"> public void setRadius(double r) { - radius = r; - }</programlisting> + <programlisting language="java">public void setRadius(double r) { + radius = r; +}</programlisting> <para>Note that we have chosen a different value for the method's formal radius parameter to be <quote>r</quote> rather than @@ -1099,9 +1099,9 @@ public class Circle { making it easier for a programmer to recognize the expected name in the generated <xref linkend="glo_Javadoc"/>:</para> - <programlisting language="java"> public void setRadius(double radius) { - <emphasis role="bold">this.</emphasis>radius = radius; - }</programlisting> + <programlisting language="java">public void setRadius(double radius) { +<emphasis role="red"> this.</emphasis>radius = radius; +}</programlisting> <para>This requires the usage of the <code language="java">this</code> keyword to distinguish the formal @@ -1184,18 +1184,18 @@ public class Circle { translation vector with respect to the origin (0,0). The following hint may be helpful:</para> - <programlisting language="java"> /** - * @param x The circle's x center coordinate value - */ - public void setX(double x) { - // TODO - } - /** - * @param y The circle's y center coordinate value - */ - public void setY(double y) { - // TODO - }</programlisting> + <programlisting language="java">/** + * @param x The circle's x center coordinate value + */ +public void setX(double x) { + // TODO +} +/** + * @param y The circle's y center coordinate value + */ +public void setY(double y) { + // TODO +}</programlisting> <para>You may as well extend the constructors of <classname>Rectangle</classname> and @@ -1447,17 +1447,17 @@ public void writeSvg() { </tr> </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_callout_publicPrivateInterface-1-co" - xml:id="sd1_callout_publicPrivateInterface-1"> - <para>Private attributes only accessible inside class.</para> - </callout> - - <callout arearefs="sd1_callout_publicPrivateInterface-2-co" - xml:id="sd1_callout_publicPrivateInterface-2"> - <para>Public interface accessible by arbitrary classes.</para> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_callout_publicPrivateInterface-1-co" + xml:id="sd1_callout_publicPrivateInterface-1"> + <para>Private attributes only accessible inside class.</para> + </callout> + + <callout arearefs="sd1_callout_publicPrivateInterface-2-co" + xml:id="sd1_callout_publicPrivateInterface-2"> + <para>Public interface accessible by arbitrary classes.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sd1_fig_timeAccessViolation"> @@ -2468,21 +2468,21 @@ a = 33;</programlisting></td> </tr> </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-1-co" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-1"> - <para>Reusing constructor <methodname>Rectangle(int width, int - height)</methodname> with parameters <code language="java">width = - height = 1</code>.</para> - </callout> - - <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-2-co" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-2"> - <para>Reusing constructor <methodname>Rectangle(int width, int - height)</methodname> with parameters <code language="java">width = - height = widthAndHeight</code>.</para> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-1-co" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-1"> + <para>Reusing constructor <methodname>Rectangle(int width, int + height)</methodname> with parameters <code language="java">width = + height = 1</code>.</para> + </callout> + + <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-2-co" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-2"> + <para>Reusing constructor <methodname>Rectangle(int width, int + height)</methodname> with parameters <code language="java">width = + height = widthAndHeight</code>.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sd1_fig_rectangleThreeConstructorsInstances"> @@ -2572,30 +2572,30 @@ Rectangle individual = new Rectangle(2, 7); // 2 x 7</programlisting></td> <itemizedlist> <listitem> - <programlisting language="java"> /** - * Raise the employee's salary by the given percentage. - * - * Example: If the current annual salary is 30000 € then - * raising by 2,5% will result in 30750 € - * - * @param percentage Raise the current salary by this percentage. - * - */ - public void raiseSalary(double percentage) { - <emphasis role="bold">// TODO: implement me!</emphasis> - }</programlisting> + <programlisting language="java">/** + * Raise the employee's salary by the given percentage. + * + * Example: If the current annual salary is 30000 € then + * raising by 2,5% will result in 30750 € + * + * @param percentage Raise the current salary by this percentage. + * + */ +public void raiseSalary(double percentage) { +<emphasis role="bold"> // TODO: implement me!</emphasis> +}</programlisting> </listitem> <listitem> - <programlisting language="java"> /** - * Print the employee's current state to standard output like e.g.: - * - * <pre>Age:25 + <programlisting language="java">/** + * Print the employee's current state to standard output like e.g.: + * + * <pre>Age:25 Salary:30000.00</pre> - */ - public void print() { - <emphasis role="bold">// TODO: implement me!</emphasis> - }</programlisting> + */ +public void print() { +<emphasis role="bold"> // TODO: implement me!</emphasis> +}</programlisting> </listitem> </itemizedlist> @@ -2628,29 +2628,29 @@ Salary:30600.00</screen> </question> <answer> - <programlisting language="java"> /** - * Raise the employee's salary by the given percentage. - * - * Example: If the current annual salary is 30000 € then - * raising by 2,5% will result in 30750 € - * - * @param percentage Raise the current salary by this percentage. - * - */ - public void raiseSalary(double percentage) { - salary *= (1 + percentage / 100); - } + <programlisting language="java">/** + * Raise the employee's salary by the given percentage. + * + * Example: If the current annual salary is 30000 € then + * raising by 2,5% will result in 30750 € + * + * @param percentage Raise the current salary by this percentage. + * + */ +public void raiseSalary(double percentage) { + salary *= (1 + percentage / 100); +} - /** - * Print the employee's current state to standard output like e.g.: - * - * <pre>Age:25 +/** + * Print the employee's current state to standard output like e.g.: + * + * <pre>Age:25 Salary:30000.00</pre> - */ - public void print() { - System.out.println("Age:" + age); - System.out.format("Salary:%6.2f\n", salary); - }</programlisting> +*/ +public void print() { + System.out.println("Age:" + age); + System.out.format("Salary:%6.2f\n", salary); +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -2917,14 +2917,14 @@ public class Driver { <para>There is however one apparent benefit: Developers do have better bug tracking options on offer:</para> - <programlisting language="java"> public void setSalary(double salary) { - if (salary < 0) { - <emphasis role="bold">System.err.println("This is odd: A salary may not become negative!" + - " Ask your union about minimum wages.");</emphasis> - } else { - this.salary = salary; - } - }</programlisting> + <programlisting language="java">public void setSalary(double salary) { + if (salary < 0) { + <emphasis role="bold">System.err.println("This is odd: A salary may not become negative!" + + " Ask your union about minimum wages.");</emphasis> + } else { + this.salary = salary; + } +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -2938,10 +2938,10 @@ public class Driver { <question> <para>Currently our constructor is being implemented as:</para> - <programlisting language="java"> public Employee(int ageValue, double salaryValue) { - age = ageValue; - salary = salaryValue; - }</programlisting> + <programlisting language="java">public Employee(int ageValue, double salaryValue) { + age = ageValue; + salary = salaryValue; +}</programlisting> <para>This imposes problems with respect to proper documentation. A developer will try to choose reasonable @@ -3025,11 +3025,11 @@ public class Driver { represented by the <code language="java">this</code> keyword:</para> - <programlisting language="java"> public Employee(int age, double salary) { - // The "this" keyword refers to class scope - this.age = age; - this.salary = salary; - }</programlisting> + <programlisting language="java">public Employee(int age, double salary) { + // The "this" keyword refers to class scope + this.age = age; + this.salary = salary; +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -3575,47 +3575,48 @@ seconds = 23</screen></td> } }</programlisting> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_callout_clubStaticMembercount-1-co" - xml:id="sd1_callout_clubStaticMembercount-1"> - <para>The keyword <code language="java">static</code> defines <code - language="java">memberCount</code> as a <emphasis - xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html">class - variable</emphasis> keeping track of the club's overall member - count.</para> - </callout> - - <callout arearefs="sd1_callout_clubStaticMembercount-2-co" - xml:id="sd1_callout_clubStaticMembercount-2"> - <para><code language="java">memberNumber</code> and <code - language="java">name</code> being defined as instance - variables.</para> - </callout> - - <callout arearefs="sd1_callout_clubStaticMembercount-3-co" - xml:id="sd1_callout_clubStaticMembercount-3"> - <para>Whenever a new instance of <classname>ClubMember</classname> is - being created two things happen:</para> - - <orderedlist> - <listitem> - <para>The overall <varname>memberCount</varname> variable is being - incremented.</para> - </listitem> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_callout_clubStaticMembercount-1-co" + xml:id="sd1_callout_clubStaticMembercount-1"> + <para>The keyword <code language="java">static</code> defines <code + language="java">memberCount</code> as a <emphasis + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html">class + variable</emphasis> keeping track of the club's overall member + count.</para> + </callout> - <listitem> - <para>The new club's member count is being assigned to the current - instance.</para> - </listitem> - </orderedlist> - </callout> - - <callout arearefs="sd1_callout_clubStaticMembercount-4-co" - xml:id="sd1_callout_clubStaticMembercount-4"> - <para>Accessing an instance's membership number.</para> - </callout> - </calloutlist> + <callout arearefs="sd1_callout_clubStaticMembercount-2-co" + xml:id="sd1_callout_clubStaticMembercount-2"> + <para><code language="java">memberNumber</code> and <code + language="java">name</code> being defined as instance + variables.</para> + </callout> + + <callout arearefs="sd1_callout_clubStaticMembercount-3-co" + xml:id="sd1_callout_clubStaticMembercount-3"> + <para>Whenever a new instance of <classname>ClubMember</classname> + is being created two things happen:</para> + + <orderedlist> + <listitem> + <para>The overall <varname>memberCount</varname> variable is + being incremented.</para> + </listitem> + + <listitem> + <para>The new club's member count is being assigned to the + current instance.</para> + </listitem> + </orderedlist> + </callout> + + <callout arearefs="sd1_callout_clubStaticMembercount-4-co" + xml:id="sd1_callout_clubStaticMembercount-4"> + <para>Accessing an instance's membership number.</para> + </callout> + </calloutlist> </figure> + <figure xml:id="sd1_fig_staticMembershipNumberInfo"> <title>Showing membership numbers.</title> @@ -3651,20 +3652,20 @@ seconds = 23</screen></td> ... }</programlisting> - <calloutlist role="slideExclude" > - <callout arearefs="sd1_callout_clubMembershipAccessHeadcount-1-co" - xml:id="sd1_callout_clubMembershipAccessHeadcount-1"> - <para><methodname>getMemberCount()</methodname> being defined as - <emphasis role="bold">class method</emphasis> by virtue of the <code - language="java">static</code> keyword.</para> - </callout> - - <callout arearefs="sd1_callout_clubMembershipAccessHeadcount-2-co" - xml:id="sd1_callout_clubMembershipAccessHeadcount-2"> - <para>Class (static) methods can only access class (static) - variables.</para> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_callout_clubMembershipAccessHeadcount-1-co" + xml:id="sd1_callout_clubMembershipAccessHeadcount-1"> + <para><methodname>getMemberCount()</methodname> being defined as + <emphasis role="bold">class method</emphasis> by virtue of the <code + language="java">static</code> keyword.</para> + </callout> + + <callout arearefs="sd1_callout_clubMembershipAccessHeadcount-2-co" + xml:id="sd1_callout_clubMembershipAccessHeadcount-2"> + <para>Class (static) methods can only access class (static) + variables.</para> + </callout> + </calloutlist> </figure> <figure xml:id="sd1_fig_staticAccessMemberCountImplement"> @@ -3703,8 +3704,8 @@ Club's member count:3</screen> <td valign="top"><programlisting language="java">final Helper help = new Helper(); - System.out.println("Maximum: " + - help.maximum(-3, 5));</programlisting><screen>Maximum: 5</screen></td> +System.out.println("Maximum: " + + help.maximum(-3, 5));</programlisting><screen>Maximum: 5</screen></td> </tr> </informaltable> @@ -3832,13 +3833,13 @@ model/ClubMember.java:20: error: non-static variable memberNumber <para>Instance methods may access class variables. However calling the method now requires an instance:</para> - <programlisting language="none"> final ClubMember - john = new ClubMember("John"), - karen = new ClubMember("Karen"), - petra = new ClubMember("Petra"); + <programlisting language="none">final ClubMember + john = new ClubMember("John"), + karen = new ClubMember("Karen"), + petra = new ClubMember("Petra"); - System.out.println(karen.getDetails()); - System.out.println("Club's headcount:" + <emphasis role="red">john.</emphasis>getMemberCount());</programlisting> +System.out.println(karen.getDetails()); +System.out.println("Club's headcount:" + <emphasis role="red">john.</emphasis>getMemberCount());</programlisting> <para>This is actually a regression with respect to the <code language="java">static</code> class method variant since the @@ -3861,16 +3862,16 @@ model/ClubMember.java:20: error: non-static variable memberNumber leap year related exercise. This exercise is about wrapping your implementation into a method:</para> - <programlisting language="java"> /** - * Characterizing a given year either as leap year or - * non- leap year - * - * @param year The year in question. - * @return true if the year parameter is a leap year, false otherwise. - */ - public static boolean isLeapYear(int year) { + <programlisting language="java">/** + * Characterizing a given year either as leap year or + * non- leap year + * + * @param year The year in question. + * @return true if the year parameter is a leap year, false otherwise. + */ +public static boolean isLeapYear(int year) { ... - }</programlisting> +}</programlisting> <para>Write unit tests prior to actually implementing <methodname>boolean isLeapYear(int year)</methodname>!</para> @@ -3878,11 +3879,11 @@ model/ClubMember.java:20: error: non-static variable memberNumber <para>After finishing you should also be able to test your implementation manually:</para> - <programlisting language="java"> public static void main(String[] args) { - System.out.println("Is 1800 a leap year? " + isLeapYear(1800)); - System.out.println("Is 2000 a leap year? " + isLeapYear(2000)); - System.out.println("Is 2016 a leap year? " + isLeapYear(2016)); - }</programlisting> + <programlisting language="java">public static void main(String[] args) { + System.out.println("Is 1800 a leap year? " + isLeapYear(1800)); + System.out.println("Is 2000 a leap year? " + isLeapYear(2000)); + System.out.println("Is 2016 a leap year? " + isLeapYear(2016)); +}</programlisting> <para>This should produce the following output:</para> @@ -3931,28 +3932,28 @@ public class <link <para>Obviously all negative tests will fail. We now implement the desired method:</para> - <programlisting language="java"> <link + <programlisting language="java"><link xlink:href="P/Sd1/leapYear/target/site/apidocs/de/hdm_stuttgart/sd1/leap/LeapYear.html#isLeapYear-int-">public static boolean isLeapYear(int year)</link> { - if (year % 400 == 0) { // Every 400 years we do have a leap year. - return true; - } else if (year % 4 == 0 && 0 != year % 100) { // Every 4 years we do have a leap - return true; // year unless the year in - // question is a multiple of 100. - } else { - return false; - } - }</programlisting> + if (year % 400 == 0) { // Every 400 years we do have a leap year. + return true; + } else if (year % 4 == 0 && 0 != year % 100) { // Every 4 years we do have a leap + return true; // year unless the year in + // question is a multiple of 100. + } else { + return false; + } +}</programlisting> <para>This one is easy to read. Experienced programmers however prefer compact code:</para> - <programlisting language="java"> <link + <programlisting language="java"><link xlink:href="P/Sd1/leapYear/target/site/apidocs/de/hdm_stuttgart/sd1/leap/LeapYearCompact.html#isLeapYear-int-">public static boolean isLeapYear(int year)</link> { - return - year % 400 == 0 || // Every 400 years we do have a leap year. - year % 4 == 0 && 0 != year % 100; // Every 4 years we do have a leap year - // unless the year in question ... - }</programlisting> + return + year % 400 == 0 || // Every 400 years we do have a leap year. + year % 4 == 0 && 0 != year % 100; // Every 4 years we do have a leap year + // unless the year in question ... +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -4003,14 +4004,14 @@ public class <link loop:</para> <programlisting language="java"> ... - public static void while_squareNumbers(final int limit) { - System.out.println("Computing square numbers"); +public static void while_squareNumbers(final int limit) { + System.out.println("Computing square numbers"); ... - while (...) { + while (...) { ... - } - System.out.println("Finished computing square numbers"); - } ...</programlisting> + } + System.out.println("Finished computing square numbers"); +} ...</programlisting> </listitem> <listitem> @@ -4018,15 +4019,15 @@ public class <link loop:</para> <programlisting language="java"> ... - public static void while_squareNumbers(final int limit) { - System.out.println("Computing square numbers"); +public static void while_squareNumbers(final int limit) { + System.out.println("Computing square numbers"); ... - do { -... - } while(...); + do { + ... + } while(...); - System.out.println("Finished computing square numbers"); - } ...</programlisting> + System.out.println("Finished computing square numbers"); +} ...</programlisting> </listitem> </orderedlist> @@ -4079,18 +4080,18 @@ public class <link To avoid this error the loop has to be enclosed by an if- statement:</para> - <programlisting language="java"> public static void <link + <programlisting language="java">public static void <link xlink:href="P/Sd1/loop/answer/target/site/apidocs/de/hdm_stuttgart/sd1/loop/LoopExample.html#doWhile_squareNumbers-int-">doWhile_squareNumbers</link>(final int limit) { - System.out.println("Computing square numbers"); - int i = 4; - if (i < limit) { // Needed !!! - do { - System.out.println("i = " + i + ", i * i = " + i * i); - i += 3; - } while (i < limit); - } - System.out.println("Finished computing square numbers"); - }</programlisting> + System.out.println("Computing square numbers"); + int i = 4; + if (i < limit) { // Needed !!! + do { + System.out.println("i = " + i + ", i * i = " + i * i); + i += 3; + } while (i < limit); + } + System.out.println("Finished computing square numbers"); +}</programlisting> <para>This required if-clause reminds us that a <code language="java">do {...} while (...)</code> is an ill-suited @@ -4277,16 +4278,16 @@ public class <link <glossterm>Formal parameter names and variable scopes</glossterm> <glossdef> - <programlisting language="java"> /** - * Setting the interest rate common to all accounts. - * - * @param z - * the desired (global) interest rate. - */ - public static void setInterestRate(double z) { // Scope of variable "z" limited to - // just the current block {...}, - interestRate = z; // in contrast interestRate has - } // class scope.</programlisting> + <programlisting language="java">/** + * Setting the interest rate common to all accounts. + * + * @param z + * the desired (global) interest rate. + */ +public static void setInterestRate(double z) { // Scope of variable "z" limited to + // just the current block {...}, + interestRate = z; // in contrast interestRate has +} // class scope.</programlisting> <para>The formal variable's name <quote><code language="java">z</code></quote> may be @@ -4294,9 +4295,9 @@ public class <link non-conflicting value like <quote><code language="java">myFunnyVariableName</code></quote>:</para> - <programlisting language="java"> public static void setInterestRate(double myFunnyVariableName) { - interestRate = myFunnyVariableName; - }</programlisting> + <programlisting language="java">public static void setInterestRate(double myFunnyVariableName) { + interestRate = myFunnyVariableName; +}</programlisting> <para>Alternatively name shadowing conflicts may be resolved by using the keyword <emphasis><code @@ -4425,45 +4426,45 @@ public class <link language="java">defaultInterestRate</code> to cover negative balance values:</para> - <programlisting language="java"> private static double - interestRate = 1.5, // applied to positive balances - <emphasis role="bold">defaultInterestRate = 15.; // applied to negative balances</emphasis></programlisting> + <programlisting language="java">private static double +interestRate = 1.5, // applied to positive balances +<emphasis role="bold">defaultInterestRate = 15.; // applied to negative balances</emphasis></programlisting> <para>We need the appropriate getter and setter methods in <classname xlink:href="P/Sd1/interest/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/interest/Account.html">Account</classname>:</para> - <programlisting language="java"> /** - * @return - * the current default interest rate value. - */ - public static double <link + <programlisting language="java">/** + * @return + * the current default interest rate value. + */ +public static double <link xlink:href="P/Sd1/interest/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/interest/Account.html#getDefaultInterestRate--">getDefaultInterestRate()</link> { - return defaultInterestRate; - } + return defaultInterestRate; +} - /** - * This interest rate will be applied to negative balances. In contrast - * {{@link #setInterestRate(double)} will handle positive balance values. - * - * @param defaultInterestRate - * the desired default interest rate value. - */ - public static void <link +/** + * This interest rate will be applied to negative balances. In contrast + * {{@link #setInterestRate(double)} will handle positive balance values. + * + * @param defaultInterestRate + * the desired default interest rate value. + */ +public static void <link xlink:href="P/Sd1/interest/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/interest/Account.html#setDefaultInterestRate-double-">setDefaultInterestRate(double defaultInterestRate)</link> { - Account.defaultInterestRate = defaultInterestRate; - }</programlisting> + Account.defaultInterestRate = defaultInterestRate; +}</programlisting> <para>The computed interest depends on positive or negative balance values:</para> - <programlisting language="java"> public void applyInterest(int years) { - if (0 < balance) { - balance = balance * Math.pow((1 + interestRate / 100), years) ; - } else if (balance < 0){ - balance = balance * Math.pow((1 + defaultInterestRate / 100), years) ; - } - }</programlisting> + <programlisting language="java">public void applyInterest(int years) { + if (0 < balance) { + balance = balance * Math.pow((1 + interestRate / 100), years) ; + } else if (balance < 0){ + balance = balance * Math.pow((1 + defaultInterestRate / 100), years) ; + } +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -4579,12 +4580,12 @@ long sum = (long)a + b;</programlisting> <question> <para>Consider the following code fragment:</para> - <programlisting language="java"> int a = 6, - b = 7, - c = -3, - result = 0; + <programlisting language="java">int a = 6, + b = 7, + c = -3, + result = 0; - result += ++a - b++ + --c;</programlisting> +result += ++a - b++ + --c;</programlisting> <para>Rewrite this code by decomposing the last line into several lines to make the code easier to understand.</para> @@ -4605,14 +4606,15 @@ long sum = (long)a + b;</programlisting> language="java">result</code> (postfix notation). The following code snippet is thus equivalent:</para> - <programlisting language="java"> int a = 6, - b = 7, - c = -3, - result = 0; - ++a; - --c; - result += a - b + c; // or even: result = result + a - b + c; - b++;</programlisting> + <programlisting language="java">int a = 6, + b = 7, + c = -3, + result = 0; + +++a; +--c; +result += a - b + c; // or even: result = result + a - b + c; +b++;</programlisting> </answer> </qandaentry> </qandadiv> @@ -4815,11 +4817,11 @@ long sum = (long)a + b;</programlisting> </m:math> </inlineequation> ?</para> - <programlisting language="java"> // Numerator product n (n - 1) ... (n - k + 1) - long numerator = 1; - for (int i = n - k + 1; i <= n; i++) { - numerator *= i; - }</programlisting> + <programlisting language="java">// Numerator product n (n - 1) ... (n - k + 1) +long numerator = 1; +for (int i = n - k + 1; i <= n; i++) { + numerator *= i; +}</programlisting> <para>In this case our numerator variable of type <code language="java">long</code> will be set to a value 22! @@ -4834,14 +4836,14 @@ long sum = (long)a + b;</programlisting> <tr> <th>Code</th> - <td valign="top"><programlisting language="java"> public static void main(String[] args) { - long factorial = 1; + <td valign="top"><programlisting language="java">public static void main(String[] args) { + long factorial = 1; - for (int i = 2; i < 22; i++) { - factorial *= i; - System.out.println(factorial); - } - }</programlisting></td> + for (int i = 2; i < 22; i++) { + factorial *= i; + System.out.println(factorial); + } +}</programlisting></td> </tr> <tr> @@ -5045,19 +5047,19 @@ Largest long value:9223372036854775807</screen></td> </m:math> </inlineequation> having identical value:</para> - <programlisting language="java"> public static long binomial(int n, int k) { + <programlisting language="java">public static long binomial(int n, int k) { - // Trying to avoid arithmetic overflow using: - // n n - // ( ) = ( ) - // k n-k - // - if (n - k < k) { - k = n - k; - } + // Trying to avoid arithmetic overflow using: + // n n + // ( ) = ( ) + // k n-k + // + if (n - k < k) { + k = n - k; + } - // Numerator product n (n - 1) ... (n - k + 1) - long numerator = 1; + // Numerator product n (n - 1) ... (n - k + 1) + long numerator = 1; ...</programlisting> <para>Finally our lottery code from <xref @@ -5072,15 +5074,15 @@ Largest long value:9223372036854775807</screen></td> <tr> <th>Code</th> - <td valign="top"><programlisting language="java"> final int - totalNumberCount = 49, - drawnNumberCount = 6; + <td valign="top"><programlisting language="java">final int + totalNumberCount = 49, + drawnNumberCount = 6; - System.out.println( - "Your chance to win when drawing " + drawnNumberCount + - " out of " + totalNumberCount + - " is 1 : " + <emphasis role="bold">Binomial.binomial(totalNumberCount, drawnNumberCount))</emphasis>; - }</programlisting></td> +System.out.println( + "Your chance to win when drawing " + drawnNumberCount + + " out of " + totalNumberCount + + " is 1 : " + <emphasis role="bold">Binomial.binomial(totalNumberCount, drawnNumberCount))</emphasis>; +}</programlisting></td> </tr> <tr> @@ -5135,11 +5137,11 @@ Largest long value:9223372036854775807</screen></td> getGcd(long, long) inside a class <classname>Math</classname>:</para> - <programlisting language="java"> public static long getGcd(long a, long b) <co + <programlisting language="java">public static long getGcd(long a, long b) <co xml:id="sd1ListEuclidNeg"/> { - // Following http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html - return ??; - }</programlisting> + // Following http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html + return ??; <emphasis role="red">//TODO</emphasis> +}</programlisting> <para>With respect to fractions one or both parameters <code language="java">a</code> and <code language="java">b</code> @@ -5195,22 +5197,22 @@ Largest long value:9223372036854775807</screen></td> <para>Implementing <methodname xlink:href="P/Sd1/Gcd/V1/target/site/apidocs/de/hdm_stuttgart/mi/sd1/gcd/Math.html#getGcd-long-long-">getGcd(</methodname>...):</para> - <programlisting language="java"> public static long <link + <programlisting language="java">public static long <link xlink:href="P/Sd1/Gcd/V1/target/site/apidocs/de/hdm_stuttgart/mi/sd1/gcd/Math.html#getCommonMultiple-long-long-">getGcd(long a, long b)</link> { - // Following http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html - if (a < b) { // Swap the values of a and b - long tmp = a; - a = b; - b = tmp; - } - while (0 != b) { - long r = a % b; - a = b; - b = r; - } - return a; - }</programlisting> + // Following http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html + if (a < b) { // Swap the values of a and b + final long tmp = a; + a = b; + b = tmp; + } + while (0 != b) { + final long r = a % b; + a = b; + b = r; + } + return a; +}</programlisting> <para>Knowing the the <acronym>gcd</acronym> of two values a and b the common multiple may be obtained by <inlineequation> @@ -5251,15 +5253,15 @@ Largest long value:9223372036854775807</screen></td> </m:math> </inlineequation>. Thus we have:</para> - <programlisting language="java"> public static long <link + <programlisting language="java">public static long <link xlink:href="P/Sd1/Gcd/V1/target/site/apidocs/de/hdm_stuttgart/mi/sd1/gcd/Math.html#getGcd-long-long-">getLeastCommonMultiple(long a, long b)</link> { - final long gcd = getGcd(a, b); - if (1 == gcd) { - return a * b; - } else { - return (a / gcd) * b; - } - }</programlisting> + final long gcd = getGcd(a, b); + if (1 == gcd) { + return a * b; + } else { + return (a / gcd) * b; + } +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -5577,21 +5579,21 @@ Archive: .../.m2/repository/.../sd1/helper/0.9/helper-0.9.jar a fraction we simply divide both numerator and denominator by the <acronym>GCD</acronym> value:</para> - <programlisting language="java"> <link + <programlisting language="java"><link xlink:href="P/Sd1/fraction/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/fraction/Fraction.html#Fraction-long-long-">public Fraction(long numerator, long denominator)</link> { - final long gcd = Math.getGcd(numerator, denominator); + final long gcd = Math.getGcd(numerator, denominator); - setNumerator(numerator / gcd); - setDenominator(denominator / gcd); - }</programlisting> + setNumerator(numerator / gcd); + setDenominator(denominator / gcd); +}</programlisting> <para>Its tempting to implement <methodname>mult(...)</methodname> in a simple fashion:</para> - <programlisting language="java"> public Fraction mult2(Fraction f) { - return new Fraction(numerator * f.numerator, + <programlisting language="java">public Fraction mult2(Fraction f) { + return new Fraction(numerator * f.numerator, denominator * f.denominator); - }</programlisting> +}</programlisting> <para>This is however too shortsighted. Consider the example <inlineequation> @@ -5660,14 +5662,14 @@ Archive: .../.m2/repository/.../sd1/helper/0.9/helper-0.9.jar </m:math> </inlineequation>. We should thus implement:</para> - <programlisting language="java"> public Fraction <link + <programlisting language="java">public Fraction <link xlink:href="P/Sd1/fraction/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/fraction/Fraction.html#mult-de.hdm_stuttgart.mi.sd1.fraction.Fraction-">mult(Fraction f)</link> { - final Fraction f1 = new Fraction(f.numerator, denominator), - f2 = new Fraction(numerator, f.denominator); + final Fraction f1 = new Fraction(f.numerator, denominator), + f2 = new Fraction(numerator, f.denominator); - return new Fraction(f1.numerator * f2.numerator, - f1.denominator * f2.denominator); - }</programlisting> + return new Fraction(f1.numerator * f2.numerator, + f1.denominator * f2.denominator); +}</programlisting> <para>Similar reflections lead to the clue decomposing the denominators when implementing @@ -5675,35 +5677,35 @@ Archive: .../.m2/repository/.../sd1/helper/0.9/helper-0.9.jar if your task was adding two fractions by hand trying to avoid large numbers:</para> - <programlisting language="java"> public Fraction <link + <programlisting language="java">public Fraction <link xlink:href="P/Sd1/fraction/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/fraction/Fraction.html#add-de.hdm_stuttgart.mi.sd1.fraction.Fraction-">add(Fraction f)</link> { - final long gcd = Math.getGcd(denominator, f.denominator); + final long gcd = Math.getGcd(denominator, f.denominator); - return new Fraction( numerator * (f.denominator / gcd) + - (denominator / gcd) * f.numerator, (denominator / gcd) * f.denominator); - }</programlisting> + return new Fraction( numerator * (f.denominator / gcd) + + (denominator / gcd) * f.numerator, (denominator / gcd) * f.denominator); +}</programlisting> <para>See complete <link xlink:href="P/Sd1/fraction/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/fraction/Fraction.html">implementation here</link>. We may re-use out test:</para> - <programlisting language="java"> public static void <link + <programlisting language="java">public static void <link xlink:href="P/Sd1/fraction/V2/target/site/apidocs/de/hdm_stuttgart/mi/sd1/fraction/Driver.html#main-java.lang.String:A-">main(String[] args)</link> { - // Input - final Fraction - twoThird = new Fraction(2, 3), // Construct a fraction object (2/3) - threeSeven = new Fraction(3, 7); // Construct a fraction object (3/7) + // Input + final Fraction + twoThird = new Fraction(2, 3), // Construct a fraction object (2/3) + threeSeven = new Fraction(3, 7); // Construct a fraction object (3/7) - // Computed results - final Fraction - sum = twoThird.add(threeSeven), // (2/3) + (3/7) - product = twoThird.mult(threeSeven); // (2/3) * (3/7) + // Computed results + final Fraction + sum = twoThird.add(threeSeven), // (2/3) + (3/7) + product = twoThird.mult(threeSeven); // (2/3) * (3/7) - System.out.println("(2/3) + (3/7) = (23/21) = " + sum.getValue()); - System.out.println("(2/3) * (3/7) = (2/7) = " + product.getValue()); - }</programlisting> + System.out.println("(2/3) + (3/7) = (23/21) = " + sum.getValue()); + System.out.println("(2/3) * (3/7) = (2/7) = " + product.getValue()); +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -5828,20 +5830,19 @@ public class Math { <para>Implement the following method:</para> - <programlisting language="java"> /** - * Computing the factorial of a given argument. - * - * @param n - * Zero or any positive integer - * - * @return - * The product 1 x 2 x 3 x ... x n or 1 in case of n == 0. In case of an - * arithmetic overflow a value of {@link Long#MAX_VALUE} is being returned. - */ - static public long factorial(int n) { - - // TODO: implement me! - }</programlisting> + <programlisting language="java">/** + * Computing the factorial of a given argument. + * + * @param n + * Zero or any positive integer + * + * @return + * The product 1 x 2 x 3 x ... x n or 1 in case of n == 0. In case of an + * arithmetic overflow a value of {@link Long#MAX_VALUE} is being returned. + */ +static public long factorial(int n) { + // TODO: implement me! +}</programlisting> <orderedlist> <listitem> @@ -5881,21 +5882,22 @@ public class Math { among the <xref linkend="glo_Java"/> built-in integer types. Consider the following example code:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - System.out.println("Max long value:" + Long.MAX_VALUE + "\n"); - for (int i = 15; i < 23; i++) { - System.out.println(i + ":" + factorial(i)); - } - } - static public long factorial(int n) { + System.out.println("Max long value:" + Long.MAX_VALUE + "\n"); + for (int i = 15; i < 23; i++) { + System.out.println(i + ":" + factorial(i)); + } +} - long ret = 1; - for (int i = n; 1 < i; i--) { - ret *= i; - } - return ret; - }</programlisting> +static public long factorial(int n) { + + long ret = 1; + for (int i = n; 1 < i; i--) { + ret *= i; + } + return ret; +}</programlisting> <para>This yields:</para> @@ -6299,19 +6301,19 @@ System.out.println(factorial(3));</programlisting> <answer> <para>The implementation is surprisingly simple:</para> - <programlisting language="java"> static public long factorialRecurse(int n) { - if (0 == n) { - return 1; // Termination condition - } else { - return n * factorialRecurse(n - 1); // Reducing step: n! = n * (n - 1)! - }</programlisting> + <programlisting language="java">static public long factorialRecurse(int n) { + if (0 == n) { + return 1; // Termination condition + } else { + return n * factorialRecurse(n - 1); // Reducing step: n! = n * (n - 1)! +}</programlisting> <para>If you fancy <quote>compact</quote> code you may as well write.</para> - <programlisting language="java"> static public long factorialRecurse(int n) { return 0 == n ? 1: n * f(n - 1);}</programlisting> + <programlisting language="java">static public long factorialRecurse(int n) { return 0 == n ? 1: n * f(n - 1);}</programlisting> - <para>Beware: The latter sacrifies both readability and the + <para>Beware: The latter sacrifices both readability and the ability to debug for brevity. Your mileage may vary.</para> </answer> </qandaentry> @@ -6603,14 +6605,14 @@ System.out.println(factorial(3));</programlisting> <para>The implementation is surprisingly simple:</para> - <programlisting language="java"> public static long binomial(int n, int k) { + <programlisting language="java">public static long binomial(int n, int k) { - if (0 == k || n == k) { // End of recursion - return 1; - } else { // 0 < k < n holds true, so continue reducing - return binomial(n - 1, k) + binomial(n - 1, k - 1); - } - }</programlisting> + if (0 == k || n == k) { // End of recursion + return 1; + } else { // 0 < k < n holds true, so continue reducing + return binomial(n - 1, k) + binomial(n - 1, k - 1); + } +}</programlisting> <para>For the purpose of comparison we rename the <quote>traditional</quote> loop based implementation as @@ -6625,33 +6627,33 @@ System.out.println(factorial(3));</programlisting> <tr> <th>Code</th> - <td valign="top"><programlisting language="java"> public static void main(String[] args) { - - long recursiveTime = 0, loopTime = 0; - - for (int i = 0; i < 10; i++) { - { - final long start = System.nanoTime(); - System.out.println(Binomial.binomial(90, 6)); - final long duration = (System.nanoTime() - start); - recursiveTime += duration; - System.out.println("Recursive: Elapsed time:" + duration); - } - { - final long start = System.nanoTime(); - System.out.println(Binomial.binomialLoop(90, 6)); - final long duration = (System.nanoTime() - start); - loopTime += duration; - System.out.println("Loop: Elapsed time:" + duration); - } - System.out.println(" End of run #" + i + - " -------------------------------"); + <td valign="top"><programlisting language="java">public static void main(String[] args) { + + long recursiveTime = 0, loopTime = 0; + + for (int i = 0; i < 10; i++) { + { + final long start = System.nanoTime(); + System.out.println(Binomial.binomial(90, 6)); + final long duration = (System.nanoTime() - start); + recursiveTime += duration; + System.out.println("Recursive: Elapsed time:" + duration); } - System.out.println("Aggregated loop time: " + loopTime); - System.out.println("Aggregated recursion time: " + recursiveTime); - System.out.println("Ratio Recursive / Loop: " + - (recursiveTime / loopTime)); - }</programlisting></td> + { + final long start = System.nanoTime(); + System.out.println(Binomial.binomialLoop(90, 6)); + final long duration = (System.nanoTime() - start); + loopTime += duration; + System.out.println("Loop: Elapsed time:" + duration); + } + System.out.println(" End of run #" + i + + " -------------------------------"); + } + System.out.println("Aggregated loop time: " + loopTime); + System.out.println("Aggregated recursion time: " + recursiveTime); + System.out.println("Ratio Recursive / Loop: " + + (recursiveTime / loopTime)); +}</programlisting></td> </tr> <tr> @@ -7140,16 +7142,16 @@ Ratio Recursive / Loop: 65554</screen></td> <para>Calculating values by a finite series requires a loop:</para> - <programlisting language="java"> public static double exp(double x) { - double currentTerm = 1., // the first (i == 0) term x^0/0! - sum = currentTerm; // initialize to the power series' first term + <programlisting language="java">public static double exp(double x) { + double currentTerm = 1., // the first (i == 0) term x^0/0! + sum = currentTerm; // initialize to the power series' first term - for (int i = 1; i <= seriesLimit; i++) { // i = 0 has already been completed. - currentTerm *= x / i; - sum += currentTerm; - } - return sum; - }</programlisting> + for (int i = 1; i <= seriesLimit; i++) { // i = 0 has already been completed. + currentTerm *= x / i; + sum += currentTerm; + } + return sum; +}</programlisting> <para>You may also view the <productname>Javadoc</productname> and the implementation of <link @@ -7157,18 +7159,18 @@ Ratio Recursive / Loop: 65554</screen></td> Math.exp(double)</link>. We may use the subsequent code snippet for testing and comparing our implementation:</para> - <programlisting language="java"> Math.setSeriesLimit(6); + <programlisting language="java">Math.setSeriesLimit(6); - double byPowerSeries = Math.exp(1.); - System.out.println("e^1=" + byPowerSeries + ", difference=" + +double byPowerSeries = Math.exp(1.); +System.out.println("e^1=" + byPowerSeries + ", difference=" + (byPowerSeries - java.lang.Math.exp(1.))); - byPowerSeries = Math.exp(2.); - System.out.println("e^2=" + byPowerSeries + ", difference=" + +byPowerSeries = Math.exp(2.); +System.out.println("e^2=" + byPowerSeries + ", difference=" + (byPowerSeries - java.lang.Math.exp(2.))); - byPowerSeries = Math.exp(3.); - System.out.println("e^3=" + byPowerSeries + ", difference=" + +byPowerSeries = Math.exp(3.); +System.out.println("e^3=" + byPowerSeries + ", difference=" + (byPowerSeries - java.lang.Math.exp(3.)));</programlisting> <para>In comparison with a professional implementation we have @@ -7944,12 +7946,12 @@ sin(4 * PI)=4518.2187229323445, difference=4518.2187229323445</screen> value can only be approximated by an in memory representation of eight bytes. Consider the following example:</para> - <programlisting language="java"> double one = 1., - a = 0.000000000000200, - b = 0.000000000000201; + <programlisting language="java">double one = 1., + a = 0.000000000000200, + b = 0.000000000000201; - System.out.println("(1 + (a - b)) - 1:" + ((one + (a - b)) - one)); - System.out.println("((1 + a) - b) - 1:" + (((one + a) - b) - one));</programlisting> +System.out.println("(1 + (a - b)) - 1:" + ((one + (a - b)) - one)); +System.out.println("((1 + a) - b) - 1:" + (((one + a) - b) - one));</programlisting> <para>This produces the following output:</para> @@ -8798,23 +8800,23 @@ sin(4 * PI)=4518.2187229323445, difference=4518.2187229323445</screen> <para>Now we need two steps mapping our argument:</para> - <programlisting language="java"> public static double sin(double x) { - // Step 1: Normalize x to [-PI, +PI[ - final long countTimes2PI = (long) java.lang.Math.rint(x / 2 / PI); - if (countTimes2PI != 0) { - x -= 2 * PI * countTimes2PI; - } + <programlisting language="java">public static double sin(double x) { + // Step 1: Normalize x to [-PI, +PI[ + final long countTimes2PI = (long) java.lang.Math.rint(x / 2 / PI); + if (countTimes2PI != 0) { + x -= 2 * PI * countTimes2PI; + } - // Step 2: Normalize x to [-PI/2, +PI/2] - // Since sin(x) = sin (PI - x) we continue to normalize - // having x in [-PI/2, +PI/2] - if (PI/2 < x) { - x = PI - x; - } else if (x < -PI/2) { - x = -x - PI; - } + // Step 2: Normalize x to [-PI/2, +PI/2] + // Since sin(x) = sin (PI - x) we continue to normalize + // having x in [-PI/2, +PI/2] + if (PI/2 < x) { + x = PI - x; + } else if (x < -PI/2) { + x = -x - PI; + } - // Step 3: Continue with business as usual + // Step 3: Continue with business as usual ...</programlisting> <para>This yet sows only the result from applying the first @@ -9352,26 +9354,26 @@ After printDuplicateValue: <emphasis role="red">6</emphasis></screen></td> </imageobjectco> </mediaobject> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_fig_callStackCircleAreaIdea-1-co" - xml:id="sd1_fig_callStackCircleAreaIdea-1"> - <para>Three call stack frames corresponding to - <methodname>main()</methodname> calling - <methodname>circleArea(2)</methodname> calling - <methodname>square(2)</methodname>.</para> - </callout> - - <callout arearefs="sd1_fig_callStackCircleAreaIdea-2-co" - xml:id="sd1_fig_callStackCircleAreaIdea-2"> - <para>Local variables corresponding to selected stack frame.</para> - - <tip> - <para>In the above example you may select stack frame - <quote>circleArea</quote> showing its local variables while leaving - your debugger resting at line 3.</para> - </tip> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_fig_callStackCircleAreaIdea-1-co" + xml:id="sd1_fig_callStackCircleAreaIdea-1"> + <para>Three call stack frames corresponding to + <methodname>main()</methodname> calling + <methodname>circleArea(2)</methodname> calling + <methodname>square(2)</methodname>.</para> + </callout> + + <callout arearefs="sd1_fig_callStackCircleAreaIdea-2-co" + xml:id="sd1_fig_callStackCircleAreaIdea-2"> + <para>Local variables corresponding to selected stack frame.</para> + + <tip> + <para>In the above example you may select stack frame + <quote>circleArea</quote> showing its local variables while + leaving your debugger resting at line 3.</para> + </tip> + </callout> + </calloutlist> </figure> </section> @@ -9661,21 +9663,21 @@ java.lang.AssertionError </imageobjectco> </mediaobject> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_fig_testSkeletonImplementation-1-co" - xml:id="sd1_fig_testSkeletonImplementation-1"> - <para>Test <methodname>test_1_isNotPrime()</methodname> accidentally - failing due to dummy implementation <xref - linkend="sd1_fig_UnitTestingStep_1"/>.</para> - </callout> - - <callout arearefs="sd1_fig_testSkeletonImplementation-2-co" - xml:id="sd1_fig_testSkeletonImplementation-2"> - <para>Test <methodname>test_2_isPrime()</methodname> accidentally - succeeding due to dummy implementation <xref - linkend="sd1_fig_UnitTestingStep_1"/>.</para> - </callout> - </calloutlist> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_fig_testSkeletonImplementation-1-co" + xml:id="sd1_fig_testSkeletonImplementation-1"> + <para>Test <methodname>test_1_isNotPrime()</methodname> accidentally + failing due to dummy implementation <xref + linkend="sd1_fig_UnitTestingStep_1"/>.</para> + </callout> + + <callout arearefs="sd1_fig_testSkeletonImplementation-2-co" + xml:id="sd1_fig_testSkeletonImplementation-2"> + <para>Test <methodname>test_2_isPrime()</methodname> accidentally + succeeding due to dummy implementation <xref + linkend="sd1_fig_UnitTestingStep_1"/>.</para> + </callout> + </calloutlist> </figure> <para>Before replacing the skeleton implementation <xref @@ -9765,13 +9767,13 @@ Results : <title>Changing the implementation</title> <programlisting language="none">public static boolean isPrime(int value) { - for (int i = 2; <emphasis role="red">i * i</emphasis> < value; i++) { - if (0 == value % i) { - return false; - } + for (int i = 2; <emphasis role="red">i * i</emphasis> < value; i++) { + if (0 == value % i) { + return false; } - return value != 1; - }</programlisting> + } + return value != 1; +}</programlisting> </figure> <figure xml:id="sd1_fig_primeRegressionTest"> @@ -9789,13 +9791,13 @@ Results : <programlisting language="none">public static boolean <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/Doc/Sd1/Ref/ObjectsAndClasses/Tests/Prime_v02/src/main/java/de/hdm_stuttgart/mi/sd1/Prime.java">isPrime</link>(int value) { - for (int i = 2; i * i <emphasis role="red"><=</emphasis> value; i++) { - if (0 == value % i) { - return false; - } + for (int i = 2; i * i <emphasis role="red"><=</emphasis> value; i++) { + if (0 == value % i) { + return false; } - return value != 1; - }</programlisting> + } + return value != 1; +}</programlisting> </figure> <figure xml:id="sd1_fig_primeRegressionTestFinal"> @@ -9910,16 +9912,16 @@ at qq.doubleCompareTest.test1_3(<emphasis role="red">doubleCompareTest.java:15</ <para>Implement the following method by using a loop:</para> - <programlisting language="java"> /** - * Summing up all integers starting from 0 up to and including a given limit - * Example: Let the limit be 5, then the result is 1 + 2 + 3 + 4 + 5 - * - * @param limit The last number to include into the computed sum - * @return The sum of 1 + 2 + ... + limit - */ - public static long getSum (int limit) { - ... - }</programlisting> + <programlisting language="java">/** + * Summing up all integers starting from 0 up to and including a given limit + * Example: Let the limit be 5, then the result is 1 + 2 + 3 + 4 + 5 + * + * @param limit The last number to include into the computed sum + * @return The sum of 1 + 2 + ... + limit + */ +public static long getSum (int limit) { + ... +}</programlisting> <para>For the sake of getting used to it write some unit tests beforehand.</para> diff --git a/Doc/Sd1/statements.xml b/Doc/Sd1/statements.xml index c41c92cde..f1ca42a2d 100644 --- a/Doc/Sd1/statements.xml +++ b/Doc/Sd1/statements.xml @@ -1057,18 +1057,18 @@ You entered 1234567</screen> number of points to the variable <code language="java">newResult</code>.</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int pointsReached = 1; - int maximumPoints = 12; - int pointsToAdd = 3; + int pointsReached = 1; + int maximumPoints = 12; + int pointsToAdd = 3; - final int newResult; + final int newResult; - // TODO: Assignment to variable newResult + // TODO: Assignment to variable newResult - System.out.println("New Result:" + newResult); - }</programlisting> + System.out.println("New Result:" + newResult); +}</programlisting> </question> <answer> @@ -1077,40 +1077,39 @@ You entered 1234567</screen> language="java">pointsToAdd</code>. When exceeding the limit we just assign the limit itself:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int pointsReached = 1; - int maximumPoints = 12; - int pointsToAdd = 3; + final int pointsReached = 1; + final int maximumPoints = 12; + final int pointsToAdd = 3; - final int newResult; + final int newResult; - if (maximumPoints <= pointsReached + pointsToAdd) { - newResult = maximumPoints; - } else { - newResult = pointsReached + pointsToAdd; - } + if (maximumPoints <= pointsReached + pointsToAdd) { + newResult = maximumPoints; + } else { + newResult = pointsReached + pointsToAdd; + } - System.out.println("New Result:" + newResult); - }</programlisting> + System.out.println("New Result:" + newResult); +}</programlisting> <para>This basically means calculating the minimum of the two expressions <code language="java">pointsReached + pointsToAdd</code> and <code language="java">maximumPoints</code>. This may as well be be implemented by:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - int pointsReached = 1; - int maximumPoints = 12; - int pointsToAdd = 3; + final int pointsReached = 1; + final int maximumPoints = 12; + final int pointsToAdd = 3; - final int newResult = <link + final int newResult = <link xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#min(int,int)">Math.min</link>(maximumPoints, pointsReached + pointsToAdd); - System.out.println("New Result:" + newResult); - - }</programlisting> + System.out.println("New Result:" + newResult); +}</programlisting> <para>You will fully understand the above expression <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html">Math</classname>.<methodname @@ -1899,21 +1898,21 @@ public class LeapYear { combining the first and third <code language="java">if</code> branch into one resolves the issue:</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final Scanner scan = new Scanner(System.in); // Read user input - System.out.print("Enter a year:>"); - final int year = scan.nextInt(); - scan.close(); + final Scanner scan = new Scanner(System.in); // Read user input + System.out.print("Enter a year:>"); + final int year = scan.nextInt(); + scan.close(); - if (0 == year % 400 || <emphasis role="bold">// Every 400 years we do have a leap year.</emphasis> - (0 == year % 4 && <emphasis role="bold">// Every 4 years we do have a leap year</emphasis> - 0 != year % 100)) { <emphasis role="bold">// unless year is a multiple of 100.</emphasis> - System.out.println("Year " + year + " is a leap year"); - } else { - System.out.println("Year " + year + " is no leap year"); - } - }</programlisting> + if (0 == year % 400 || <emphasis role="bold">// Every 400 years we do have a leap year.</emphasis> + (0 == year % 4 && <emphasis role="bold">// Every 4 years we do have a leap year</emphasis> + 0 != year % 100)) { <emphasis role="bold">// unless year is a multiple of 100.</emphasis> + System.out.println("Year " + year + " is a leap year"); + } else { + System.out.println("Year " + year + " is no leap year"); + } +}</programlisting> <para>Some enthusiasts prefer compact expressions at the expense of readability (»Geek syndrome«). The following code is fully @@ -2651,59 +2650,59 @@ for (int row = 0; row < numberOfRows; row++) { </listitem> </orderedlist> - <programlisting language="java"> public static void main(String[] args) { - - // Example: 6 rows, tree's body loop index ranging from 0 to 5 - // - // X The tree's top. - // 0 * - // 1 *** - // 2 ***** - // 3 ******* The tree's body. - // 4 ********* - // 5 *********** - // III The tree's two bottom trunk lines. - // III - - final int numberOfRows = 6; // You may easily change this value. - - // Part one: The tree's top - // - for (int x = 0; x < numberOfRows; x++) { // Printing the tree's top. We need - System.out.print(' '); // numberOfRows preceeding spaces - } // before printing the - System.out.println("X"); // 'X' (top) character. - - // Part two: The tree's body - // - for (int row = 0; row < numberOfRows ; row++) { // Outer loop printing the - // tree's body. - - for (int x = 0; x < numberOfRows - row;x++) { // Starting each line with - System.out.print(' '); // (numberOfRows - row) - } // space characters ... - - for (int x = 0; x < 2 * row + 1; x ++) { // .. then printing (2*row+1) - // body ('*') characters ... - System.out.print('*'); // May try <xref + <programlisting language="java">public static void main(String[] args) { + + // Example: 6 rows, tree's body loop index ranging from 0 to 5 + // + // X The tree's top. + // 0 * + // 1 *** + // 2 ***** + // 3 ******* The tree's body. + // 4 ********* + // 5 *********** + // III The tree's two bottom trunk lines. + // III + + final int numberOfRows = 6; // You may easily change this value. + + // Part one: The tree's top + // + for (int x = 0; x < numberOfRows; x++) { // Printing the tree's top. We need + System.out.print(' '); // numberOfRows preceeding spaces + } // before printing the + System.out.println("X"); // 'X' (top) character. + + // Part two: The tree's body + // + for (int row = 0; row < numberOfRows ; row++) { // Outer loop printing the + // tree's body. + + for (int x = 0; x < numberOfRows - row;x++) { // Starting each line with + System.out.print(' '); // (numberOfRows - row) + } // space characters ... + + for (int x = 0; x < 2 * row + 1; x ++) { // .. then printing (2*row+1) + // body ('*') characters ... + System.out.print('*'); // May try <xref linkend="glo_unicode"/> '▲' instead - } - System.out.print("\n"); // ... and finally terminating the - } // current body row. + } + System.out.print("\n"); // ... and finally terminating the + } // current body row. - // Part three: The tree's bottom trunk - // - for (int x = 0; x < numberOfRows-1; x++) { // Preparing the first line + // Part three: The tree's bottom trunk + // + for (int x = 0; x < numberOfRows-1; x++) { // Preparing the first line - System.out.print(' '); // of bottom trunk part ... - } - System.out.println("###"); // ... finished. + System.out.print(' '); // of bottom trunk part ... + } + System.out.println("###"); // ... finished. - for (int x = 0; x < numberOfRows-1; x++) { // Preparing the second - System.out.print(' '); // line of bottom trunk - } //part ... - System.out.println("###"); // ... finished. - }</programlisting> + for (int x = 0; x < numberOfRows-1; x++) { // Preparing the second + System.out.print(' '); // line of bottom trunk + } // part ... + System.out.println("###"); // ... finished. +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -2744,84 +2743,84 @@ for (int row = 0; row < numberOfRows; row++) { <para>We start from a version being fully covered by our current knowledge:</para> - <programlisting language="java"> public static void main(String[] args) { - - // Example: 5 row groups, tree's body loop index ranging from 0 to 4 - - // \ / The tree's top. - // -->*<-- - // /_\ - // 0 /_\_\ Start of tree's body - // /_/_/_\ - // 1 /_\_\_\ - // /_/_/_/_\ - // 2 /_\_\_\_\ - // /_/_/_/_/_\ - // 3 /_\_\_\_\_\ - // /_/_/_/_/_/_\ - // 4 /_\_\_\_\_\_\ - // /_/_/_/_/_/_/_\ End of tree's body - // [___] Bottom trunk line. - - - final int numberOfRowGroups = 5; // You may easily change this - // value. - // Part one: The tree's top - // - for (int x = 0; x < numberOfRowGroups + 1; x++) { // Printing the tree's very - // top. We need numberOfRows+1 - System.out.print(' '); // preceding spaces - } // before printing the - System.out.println("\\ /"); // "\ /" String. - - for (int x = 0; x < numberOfRowGroups - 1; x++) { // Printing the tree's top '*' - // We need numberOfRows-1 - System.out.print(' '); // preceding spaces - } // before printing the - System.out.println("-->*<--"); // "-->*<--" string. - - for (int x = 0; x < numberOfRowGroups + 1; x++) { // The tree's lower top "/ \". - System.out.print(' '); // We need again numberOfRows+1 - } // preceding spaces. - System.out.println("/_\\"); - - // Part two: The tree's body - // - for (int rowGroup = 0; // Outer loop printing the - rowGroup < numberOfRowGroups; rowGroup++) { // tree's body. - - // First body line of current group - // - for (int x = 0; // Starting first line - x < numberOfRowGroups - rowGroup;x++) { // of row group with + <programlisting language="java">public static void main(String[] args) { + + // Example: 5 row groups, tree's body loop index ranging from 0 to 4 + + // \ / The tree's top. + // -->*<-- + // /_\ + // 0 /_\_\ Start of tree's body + // /_/_/_\ + // 1 /_\_\_\ + // /_/_/_/_\ + // 2 /_\_\_\_\ + // /_/_/_/_/_\ + // 3 /_\_\_\_\_\ + // /_/_/_/_/_/_\ + // 4 /_\_\_\_\_\_\ + // /_/_/_/_/_/_/_\ End of tree's body + // [___] Bottom trunk line. + + + final int numberOfRowGroups = 5; // You may easily change this + // value. + // Part one: The tree's top + // + for (int x = 0; x < numberOfRowGroups + 1; x++) { // Printing the tree's very + // top. We need numberOfRows+1 + System.out.print(' '); // preceding spaces + } // before printing the + System.out.println("\\ /"); // "\ /" String. + + for (int x = 0; x < numberOfRowGroups - 1; x++) { // Printing the tree's top '*' + // We need numberOfRows-1 + System.out.print(' '); // preceding spaces + } // before printing the + System.out.println("-->*<--"); // "-->*<--" string. + + for (int x = 0; x < numberOfRowGroups + 1; x++) { // The tree's lower top "/ \". + System.out.print(' '); // We need again numberOfRows+1 + } // preceding spaces. + System.out.println("/_\\"); + + // Part two: The tree's body + // + for (int rowGroup = 0; // Outer loop printing the + rowGroup < numberOfRowGroups; rowGroup++) { // tree's body. + + // First body line of current group + // + for (int x = 0; // Starting first line + x < numberOfRowGroups - rowGroup;x++) { // of row group with // (numberOfRows - row) - System.out.print(' '); // space characters ... - } - System.out.print("/"); // Start of current row group's - for (int x = 0; x < rowGroup + 2;x++) { // first line tree body content - System.out.print("_\\"); // finishing. - } - System.out.println(); - - // Second body line of current group - // - for (int x = 0; // Starting second line of row - x < numberOfRowGroups - rowGroup - 1; x++) {// group with (numberOfRows - - System.out.print(' '); // row - 1) space characters ... - } - for (int x = 0; x < rowGroup + 3;x++) { // tree body content - System.out.print("/_"); - } - System.out.println("\\"); // finishing. - } + System.out.print(' '); // space characters ... + } + System.out.print("/"); // Start of current row group's + for (int x = 0; x < rowGroup + 2;x++) { // first line tree body content + System.out.print("_\\"); // finishing. + } + System.out.println(); + + // Second body line of current group + // + for (int x = 0; // Starting second line of row + x < numberOfRowGroups - rowGroup - 1; x++) { // group with (numberOfRows - + System.out.print(' '); // row - 1) space characters ... + } + for (int x = 0; x < rowGroup + 3;x++) { // tree body content + System.out.print("/_"); + } + System.out.println("\\"); // finishing. + } - // Part three: The tree's bottom trunk - // - for (int x = 0; x < numberOfRowGroups; x++) { // Indenting the bottom trunk ... - System.out.print(' '); - } - System.out.println("[___]"); // printing the trunk. - }</programlisting> + // Part three: The tree's bottom trunk + // + for (int x = 0; x < numberOfRowGroups; x++) { // Indenting the bottom trunk ... + System.out.print(' '); + } + System.out.println("[___]"); // printing the trunk. +}</programlisting> <para>This solution is a bit cumbersome: It involves a repeating task namely indenting lines by a given amount of spaces.</para> @@ -3135,36 +3134,36 @@ for (int row = 0; row < numberOfRows; row++) { </question> <answer> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int limit = 20; // The number of records to be printed + final int limit = 20; // The number of records to be printed - System.out.print( - "" + "<html xmlns='http://www.w3.org/1999/xhtml'>\n" - + " <head>\n" - + " <title>A square table</title>\n" - + " </head>\n" - + " <body>\n" - + " <table>\n"); + System.out.print( + "" + "<html xmlns='http://www.w3.org/1999/xhtml'>\n" + + " <head>\n" + + " <title>A square table</title>\n" + + " </head>\n" + + " <body>\n" + + " <table>\n"); - System.out.println(" <tr>"); - System.out.println(" <th>n</th><th>n * n</th>"); - System.out.println(" </tr>"); + System.out.println(" <tr>"); + System.out.println(" <th>n</th><th>n * n</th>"); + System.out.println(" </tr>"); - for (int i = 0; i <= limit; i++) { // Printing the table's body + for (int i = 0; i <= limit; i++) { // Printing the table's body - System.out.println(" <tr>"); - System.out.println(" <td style='text-align: right;'>" + i + + System.out.println(" <tr>"); + System.out.println(" <td style='text-align: right;'>" + i + "</td><td style='text-align: right;'>" + i * i + "</td>"); - System.out.println(" </tr>"); + System.out.println(" </tr>"); - } - System.out.print( - "" + " </table>\n" - + " </body>\n" - + "</html>\n"); - }</programlisting> + } + System.out.print( + "" + " </table>\n" + + " </body>\n" + + "</html>\n"); +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -3213,31 +3212,31 @@ for (int row = 0; row < numberOfRows; row++) { </question> <answer> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int limit = 10; // Parameter is subject to change. + final int limit = 10; // Parameter is subject to change. - System.out.print(" * | "); + System.out.print(" * | "); - for (int col = 1; col <= limit; col++) { // Header line of columns ranging - System.out.format("%3d ", col); // from 1 to limit. - } - System.out.println(); + for (int col = 1; col <= limit; col++) { // Header line of columns ranging + System.out.format("%3d ", col); // from 1 to limit. + } + System.out.println(); - System.out.print("---+"); // Header / table body separator. - for (int col = 1; col <= limit; col++) { - System.out.print("-----"); - } - System.out.println(); + System.out.print("---+"); // Header / table body separator. + for (int col = 1; col <= limit; col++) { + System.out.print("-----"); + } + System.out.println(); - for (int row = 1; row <= limit; row++) { // Printing rows. - System.out.format("%3d| ", row); - for (int col = 1; col <= limit; col++) { // Printing columns. - System.out.format("%3d ", row * col); - } - System.out.println(); - } - }</programlisting> + for (int row = 1; row <= limit; row++) { // Printing rows. + System.out.format("%3d| ", row); + for (int col = 1; col <= limit; col++) { // Printing columns. + System.out.format("%3d ", row * col); + } + System.out.println(); + } +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -3273,28 +3272,27 @@ for (int row = 0; row < numberOfRows; row++) { exercise is tiny: The <quote>inner</quote> loop must end when reaching the current row's index:</para> - <programlisting language="java"> final int limit = 10; // Parameter is subject to change. + <programlisting language="java">final int limit = 10; // Parameter is subject to change. - for (int row = 1; row <= limit; row++) { // Printing rows. - System.out.format("%3d| ", row); +for (int row = 1; row <= limit; row++) { // Printing rows. + System.out.format("%3d| ", row); - for (int col = 1; <emphasis role="bold">col <= row;</emphasis> col++) { // Printing column values until row index only. - System.out.format("%3d ", row * col); - } - System.out.println(); - } - System.out.print("---+"); // Header / table body separator. - for (int col = 1; col <= limit; col++) { - System.out.print("-----"); - } - System.out.println(); - System.out.print(" * | "); + for (int col = 1; <emphasis role="bold">col <= row;</emphasis> col++) { // Printing column values until row index only. + System.out.format("%3d ", row * col); + } + System.out.println(); +} +System.out.print("---+"); // Header / table body separator. + for (int col = 1; col <= limit; col++) { + System.out.print("-----"); + } + System.out.println(); + System.out.print(" * | "); - for (int col = 1; col <= limit; col++) { // Header line of columns ranging - System.out.format("%3d ", col); // from 1 to limit. - } - System.out.println(); -</programlisting> + for (int col = 1; col <= limit; col++) { // Header line of columns ranging + System.out.format("%3d ", col); // from 1 to limit. + } +System.out.println();</programlisting> </answer> </qandaentry> </qandadiv> @@ -3360,42 +3358,42 @@ for (int row = 0; row < numberOfRows; row++) { </question> <answer> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int - numBlocksHorizontal = 5, - numBlocksVertical = 2, - entriesPerBlock = 10; +final int + numBlocksHorizontal = 5, + numBlocksVertical = 2, + entriesPerBlock = 10; - final int numRows = numBlocksVertical * entriesPerBlock; + final int numRows = numBlocksVertical * entriesPerBlock; - for (int x = 0; x < numBlocksHorizontal; x++) { // Creating the overall - // table's head section - System.out.print(" n | n*n "); + for (int x = 0; x < numBlocksHorizontal; x++) { // Creating the overall + // table's head section + System.out.print(" n | n*n "); + } + System.out.println(); + for (int y = 0; // Blocks stacked below + y < numBlocksVertical; y++) { // another + for (int x = 0; // Supplementary separator + x < numBlocksHorizontal; x++) { // between two vertically + // adjacent blocks + System.out.print("----+----------"); + } + System.out.println(); + for (int yBlock = 0; // Stepping through values + yBlock < entriesPerBlock; yBlock++) { // vertically ... + for (int x = 0; x < numBlocksHorizontal; x++) { // and horizontally + // within each line. + final int cellValue = y * entriesPerBlock + + x * numRows + yBlock; // The individual value + // to be squared. + System.out.format("%3d | %4d ", // Pretty print output + cellValue, cellValue * cellValue); // values. } System.out.println(); - for (int y = 0; // Blocks stacked below - y < numBlocksVertical; y++) { // another - for (int x = 0; // Supplementary separator - x < numBlocksHorizontal; x++) { // between two vertically - // adjacent blocks - System.out.print("----+----------"); - } - System.out.println(); - for (int yBlock = 0; // Stepping through values - yBlock < entriesPerBlock; yBlock++) { // vertically ... - for (int x = 0; x < numBlocksHorizontal; x++) { // and horizontally - // within each line. - final int cellValue = y * entriesPerBlock - + x * numRows + yBlock; // The individual value - // to be squared. - System.out.format("%3d | %4d ", // Pretty print output - cellValue, cellValue * cellValue); // values. - } - System.out.println(); - } - } - }</programlisting> + } + } +}</programlisting> </answer> </qandaentry> </qandadiv> @@ -3468,13 +3466,13 @@ for (int row = 0; row < numberOfRows; row++) { style definitions in the generated HTML's header section being referenced from the document's body.</para> - <programlisting language="java"> public static void main(String[] args) { + <programlisting language="java">public static void main(String[] args) { - final int numBlocksHorizontal = 5, numBlocksVertical = 2, entriesPerBlock = 10; + final int numBlocksHorizontal = 5, numBlocksVertical = 2, entriesPerBlock = 10; - final int numRows = numBlocksVertical * entriesPerBlock; + final int numRows = numBlocksVertical * entriesPerBlock; - System.out.print("" + "<html xmlns='http://www.w3.org/1999/xhtml'>\n" + System.out.print("" + "<html xmlns='http://www.w3.org/1999/xhtml'>\n" + " <head>\n" + " <title>A square table</title>\n" + " <style>\n" + " table, th, td {border: 1px solid black;}\n" + " table {border-collapse: collapse;}\n" @@ -3483,50 +3481,49 @@ for (int row = 0; row < numberOfRows; row++) { + " </style>\n" + " </head>\n" + " <body>\n" + " <table>\n" + " <colgroup>\n"); - for (int x = 0; x < numBlocksHorizontal; x++) { // Creating the overall - // table's head section - if (0 == x % 2) { - System.out.println(" <col span='2'/>"); - } else { - System.out.println(" <col span='2' class='greyColumn'/>"); - } - } - System.out.println(" </colgroup>"); + for (int x = 0; x < numBlocksHorizontal; x++) { // Creating the overall + // table's head section + if (0 == x % 2) { + System.out.println(" <col span='2'/>"); + } else { + System.out.println(" <col span='2' class='greyColumn'/>"); + } + } + System.out.println(" </colgroup>"); - System.out.println(" <tr>"); - for (int x = 0; x < numBlocksHorizontal; x++) { // Creating the overall - // table's head section - System.out.println(" <th>n</th><th>n * n</th>"); - } - System.out.println(" </tr>"); + System.out.println(" <tr>"); + for (int x = 0; x < numBlocksHorizontal; x++) { // n | n^2 header line + + System.out.println(" <th>n</th><th>n * n</th>"); + } + System.out.println(" </tr>"); - System.out.println(); - for (int y = 0; y < numBlocksVertical; y++) { // Blocks stacked below - // another + System.out.println(); + for (int y = 0; y < numBlocksVertical; y++) { // Blocks stacked below + // another - System.out.println( // Block separating - " <tr><td></td></tr>"); // extra row. + System.out.println( // Block separating + " <tr><td></td></tr>"); // extra row. - for (int yBlock = 0; - yBlock < entriesPerBlock; yBlock++) { // Stepping through - // values vertically ... - System.out.println(" <tr>"); - for (int x = 0; x < numBlocksHorizontal; x++) { // and horizontally - // within each line. + for (int yBlock = 0; + yBlock < entriesPerBlock; yBlock++) { // Stepping through + // values vertically ... + System.out.println(" <tr>"); + for (int x = 0; x < numBlocksHorizontal; x++) { // and horizontally + // within each line. - final int cellValue = 1 + yBlock // The individual - + x * numRows + y * entriesPerBlock; // value to be squared. + final int cellValue = 1 + yBlock // The individual + + x * numRows + y * entriesPerBlock; // value to be squared. - System.out.println( // Pretty print output + System.out.println( // Pretty print output " <td>" + cellValue + "</td><td>" // values. + cellValue * cellValue + "</td>"); - } - System.out.println(" </tr>"); - } } - - System.out.print("" + " </table>\n" + " </body>\n" + "</html>\n"); - }</programlisting> + System.out.println(" </tr>"); + } + } + System.out.print("" + " </table>\n" + " </body>\n" + "</html>\n"); +}</programlisting> </answer> </qandaentry> </qandadiv> diff --git a/Doc/Sd1/streams.xml b/Doc/Sd1/streams.xml index 0ff4dcfff..542ec129d 100644 --- a/Doc/Sd1/streams.xml +++ b/Doc/Sd1/streams.xml @@ -112,15 +112,15 @@ final BufferedReader inputBufferedReader = new BufferedReader(fileReader);</prog <para>Two test cases deal both with readable and non-existing files: and expected exceptions:</para> - <programlisting language="java"> @Test - public void testReadFileOk() throws FileNotFoundException, IOException { - ReadFile.openStream("Testdata/input.txt"); // Existing file - } - @Test (expected=FileNotFoundException.class) // We expect this exception to be - // thrown. - public void testReadMissingFile() throws FileNotFoundException, IOException { - ReadFile.openStream("Testdata/input.java"); // Does not exist - }</programlisting> + <programlisting language="java">@Test +public void testReadFileOk() throws FileNotFoundException, IOException { + ReadFile.openStream("Testdata/input.txt"); // Existing file +} +@Test (expected=FileNotFoundException.class) // We expect this exception to be + // thrown. +public void testReadMissingFile() throws FileNotFoundException, IOException { + ReadFile.openStream("Testdata/input.java"); // Does not exist +}</programlisting> <para>Notice the second test which will only succeed if a <classname @@ -290,46 +290,46 @@ final BufferedReader inputBufferedReader = new BufferedReader(fileReader);</prog <glossterm>Counting words in a given string:</glossterm> <glossdef> - <programlisting language="java"> @Test - public void testNoWord() { - Assert.assertEquals("Just white space", 0, + <programlisting language="java">@Test +public void testNoWord() { + Assert.assertEquals("Just white space", 0, TextFileStatistics.findNoOfWords(" \t")); - } +} - @Test - public void testSingleWord() { - final String s = "We're"; - Assert.assertEquals("text='" + s + "'", 1, +@Test +public void testSingleWord() { + final String s = "We're"; + Assert.assertEquals("text='" + s + "'", 1, TextFileStatistics.findNoOfWords(s)); - } +} - @Test - public void testTwoWords() { - final String s = "We are"; - Assert.assertEquals("text='" + s + "'", 2, +@Test +public void testTwoWords() { + final String s = "We are"; + Assert.assertEquals("text='" + s + "'", 2, TextFileStatistics.findNoOfWords(s)); - } +} - @Test - public void testWordsWhiteHead() { - final String s = "\t \tBegin_space"; - Assert.assertEquals("text='" + s + "'", 1, +@Test +public void testWordsWhiteHead() { + final String s = "\t \tBegin_space"; + Assert.assertEquals("text='" + s + "'", 1, TextFileStatistics.findNoOfWords(s)); - } +} - @Test - public void testWordsWhiteTail() { - final String s = "End_space \t "; - Assert.assertEquals("text='" + s + "'", 1, +@Test +public void testWordsWhiteTail() { + final String s = "End_space \t "; + Assert.assertEquals("text='" + s + "'", 1, TextFileStatistics.findNoOfWords(s)); - } +} - @Test - public void testWhiteMulti() { - final String s = " some\t\tinterspersed \t spaces \t\t "; - Assert.assertEquals("text='" + s + "'", 3, +@Test +public void testWhiteMulti() { + final String s = " some\t\tinterspersed \t spaces \t\t "; + Assert.assertEquals("text='" + s + "'", 3, TextFileStatistics.findNoOfWords(s)); - }</programlisting> +}</programlisting> </glossdef> </glossentry> @@ -337,39 +337,39 @@ final BufferedReader inputBufferedReader = new BufferedReader(fileReader);</prog <glossterm>Analyzing test file data:</glossterm> <glossdef> - <programlisting language="java"> @Test - public void testTwoInputFiles() throws FileNotFoundException, IOException { + <programlisting language="java">@Test +public void testTwoInputFiles() throws FileNotFoundException, IOException { - final String model_css_filename = - "Testdata/model.css", // 4 lines 5 words 41 character - input_html_filename = - "Testdata/input.html"; // 9 lines 14 words 137 character + final String model_css_filename = + "Testdata/model.css", // 4 lines 5 words 41 character + input_html_filename = + "Testdata/input.html"; // 9 lines 14 words 137 character //_________________________________________ - // total 13 lines 19 words 178 character + // total 13 lines 19 words 178 character - final TextFileStatistics - model_css = new TextFileStatistics( - new BufferedReader(new FileReader(model_css_filename)), + final TextFileStatistics + model_css = new TextFileStatistics( + new BufferedReader(new FileReader(model_css_filename)), model_css_filename), - input_html = new TextFileStatistics(new BufferedReader( - new FileReader(input_html_filename)), input_html_filename); + input_html = new TextFileStatistics(new BufferedReader( + new FileReader(input_html_filename)), input_html_filename); - // File Testdata/model.css - Assert.assertEquals( 4, model_css.numLines); - Assert.assertEquals( 5, model_css.numWords); - Assert.assertEquals(41, model_css.numCharacters); + // File Testdata/model.css + Assert.assertEquals( 4, model_css.numLines); + Assert.assertEquals( 5, model_css.numWords); + Assert.assertEquals(41, model_css.numCharacters); - // File Testdata/input.html - Assert.assertEquals( 9, input_html.numLines); - Assert.assertEquals( 14, input_html.numWords); - Assert.assertEquals(137, input_html.numCharacters); + // File Testdata/input.html + Assert.assertEquals( 9, input_html.numLines); + Assert.assertEquals( 14, input_html.numWords); + Assert.assertEquals(137, input_html.numCharacters); - // Grand total - Assert.assertEquals( 13, TextFileStatistics.getTotalNumLines()); - Assert.assertEquals( 19, TextFileStatistics.getTotalNumWords()); - Assert.assertEquals(178, TextFileStatistics.getTotalNumCharacters()); - }</programlisting> + // Grand total + Assert.assertEquals( 13, TextFileStatistics.getTotalNumLines()); + Assert.assertEquals( 19, TextFileStatistics.getTotalNumWords()); + Assert.assertEquals(178, TextFileStatistics.getTotalNumCharacters()); +}</programlisting> </glossdef> </glossentry> </glosslist> diff --git a/Doc/Sda1/dom.xml b/Doc/Sda1/dom.xml index 0c7a6962b..956c4aab4 100644 --- a/Doc/Sda1/dom.xml +++ b/Doc/Sda1/dom.xml @@ -1,25 +1,37 @@ <?xml version="1.0" encoding="UTF-8"?> -<chapter xmlns="http://docbook.org/ns/docbook" xmlns:db="http://docbook.org/ns/docbook" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:ns="http://docbook.org/ns/transclusion" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xila="http://www.w3.org/2001/XInclude/local-attributes" xmlns:xlink="http://www.w3.org/1999/xlink" annotations="slide" version="5.1" xml:id="dom"> - <title>The Document Object Model (<acronym xlink:href="https://www.w3.org/DOM">DOM</acronym>)</title> - - <titleabbrev><acronym xlink:href="https://www.w3.org/DOM">DOM</acronym></titleabbrev> +<chapter annotations="slide" version="5.1" xml:id="dom" + xmlns="http://docbook.org/ns/docbook" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:xila="http://www.w3.org/2001/XInclude/local-attributes" + xmlns:xi="http://www.w3.org/2001/XInclude" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:ns="http://docbook.org/ns/transclusion" + xmlns:m="http://www.w3.org/1998/Math/MathML" + xmlns:html="http://www.w3.org/1999/xhtml" + xmlns:db="http://docbook.org/ns/docbook"> + <title>The Document Object Model (<acronym + xlink:href="https://www.w3.org/DOM">DOM</acronym>)</title> + + <titleabbrev><acronym + xlink:href="https://www.w3.org/DOM">DOM</acronym></titleabbrev> <figure xml:id="sda1_dom_fig_requiredKnowledge"> <title>Required knowledge</title> <itemizedlist> <listitem> - <para>Functional programming basics in <xref linkend="glo_Java" />.</para> + <para>Functional programming basics in <xref + linkend="glo_Java"/>.</para> </listitem> <listitem> - <para>Dependency management using <xref linkend="glo_Maven" />.</para> + <para>Dependency management using <xref linkend="glo_Maven"/>.</para> </listitem> </itemizedlist> </figure> <figure xml:id="sda1_dom_fig_motivationApiOverview"> - <title>Important <xref linkend="glo_XML" /> <xref linkend="glo_Java" /> + <title>Important <xref linkend="glo_XML"/> <xref linkend="glo_Java"/> APIs</title> <informaltable border="0"> @@ -32,19 +44,22 @@ <tr> <td valign="top"><itemizedlist> <listitem> - <para><link xlink:href="http://www.java2s.com/Tutorials/Java/Java_XML/0030__Java_SAX_Intro.htm">SAX</link> + <para><link + xlink:href="http://www.java2s.com/Tutorials/Java/Java_XML/0030__Java_SAX_Intro.htm">SAX</link> (push)</para> </listitem> <listitem> - <para><link xlink:href="https://docs.oracle.com/javase/tutorial/jaxp/stax/why.html">STAX</link> + <para><link + xlink:href="https://docs.oracle.com/javase/tutorial/jaxp/stax/why.html">STAX</link> (pull)</para> </listitem> </itemizedlist></td> <td valign="top"><itemizedlist> <listitem> - <para><link xlink:href="http://tutorials.jenkov.com/java-xml/dom.html">DOM</link></para> + <para><link + xlink:href="http://tutorials.jenkov.com/java-xml/dom.html">DOM</link></para> </listitem> <listitem> @@ -52,7 +67,8 @@ </listitem> <listitem> - <para><link xlink:href="https://docs.oracle.com/javase/tutorial/jaxb/intro">JAXB</link> + <para><link + xlink:href="https://docs.oracle.com/javase/tutorial/jaxb/intro">JAXB</link> <quote>Schema to classes</quote></para> </listitem> </itemizedlist></td> @@ -65,7 +81,7 @@ <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/saxmodel.pdf" scale="150" /> + <imagedata fileref="Ref/Fig/saxmodel.pdf" scale="150"/> </imageobject> </mediaobject> </figure> @@ -75,7 +91,7 @@ <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/saxapparch.pdf" scale="150" /> + <imagedata fileref="Ref/Fig/saxapparch.pdf" scale="150"/> </imageobject> </mediaobject> </figure> @@ -85,7 +101,7 @@ <mediaobject> <imageobject> - <imagedata fileref="Ref/Dom/saxAssembly.multi.svg" /> + <imagedata fileref="Ref/Dom/saxAssembly.multi.svg"/> </imageobject> </mediaobject> </figure> @@ -95,9 +111,12 @@ <titleabbrev>Language independence</titleabbrev> - <para>XML documents allow for automated content processing. The <acronym xlink:href="http://www.saxproject.org">SAX</acronym> API allows for - accessing <xref linkend="glo_XML" /> documents by <xref linkend="glo_Java" /> applications in an event based fashion. There are - however situations where <acronym xlink:href="http://www.saxproject.org">SAX</acronym> is not + <para>XML documents allow for automated content processing. The <acronym + xlink:href="http://www.saxproject.org">SAX</acronym> API allows for + accessing <xref linkend="glo_XML"/> documents by <xref + linkend="glo_Java"/> applications in an event based fashion. There are + however situations where <acronym + xlink:href="http://www.saxproject.org">SAX</acronym> is not appropriate:</para> <figure xml:id="sda1_dom_fig_saxDeficiencies"> @@ -130,9 +149,11 @@ <itemizedlist> <listitem> - <para><xref linkend="glo_DOM" /> objects and operations being defined - using <productname xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA - 2.2</productname> Interface Definition Language (<abbrev xlink:href="https://en.wikipedia.org/wiki/Interface_description_language">IDL</abbrev>)</para> + <para><xref linkend="glo_DOM"/> objects and operations being defined + using <productname + xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA + 2.2</productname> Interface Definition Language (<abbrev + xlink:href="https://en.wikipedia.org/wiki/Interface_description_language">IDL</abbrev>)</para> </listitem> <listitem> @@ -141,7 +162,7 @@ <itemizedlist> <listitem> - <para>A set of <xref linkend="glo_Java" /> interfaces.</para> + <para>A set of <xref linkend="glo_Java"/> interfaces.</para> </listitem> <listitem> @@ -161,15 +182,18 @@ </listitem> <listitem> - <para>Instantiation using the<link xlink:href="https://en.wikipedia.org/wiki/Abstract_factory_pattern"> + <para>Instantiation using the<link + xlink:href="https://en.wikipedia.org/wiki/Abstract_factory_pattern"> abstract factory pattern</link>.</para> </listitem> </itemizedlist> </figure> <figure xml:id="sda1_dom_fig_nodeDomIdl"> - <title><xref linkend="glo_DOM" /> <classname xlink:href="https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1950641247">Node</classname> - <productname xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA + <title><xref linkend="glo_DOM"/> <classname + xlink:href="https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1950641247">Node</classname> + <productname + xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA 2.2</productname> <abbrev>IDL</abbrev></title> <programlisting language="C++">interface Node { @@ -197,7 +221,8 @@ <itemizedlist> <listitem> <para>Using a given language's constructs closely resembling the - <productname xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA + <productname + xlink:href="http://www.omg.org/gettingstarted/corbafaq.htm">CORBA 2.2</productname> <abbrev>IDL</abbrev> specification.</para> </listitem> @@ -208,8 +233,9 @@ </figure> <figure xml:id="sda1_dom_fig_nodaJavaBinding"> - <title><classname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html">org.w3c.dom.Node</classname> - <xref linkend="glo_Java" /> binding.</title> + <title><classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html">org.w3c.dom.Node</classname> + <xref linkend="glo_Java"/> binding.</title> <programlisting language="java">package org.w3c.dom; @@ -231,7 +257,8 @@ public interface Node { // Node Types ...</programlisting> </figure> - <para>We take <methodname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html#getChildNodes()">org.w3c.dom.Node.getChildNodes()</methodname> + <para>We take <methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html#getChildNodes()">org.w3c.dom.Node.getChildNodes()</methodname> as an example:</para> <figure xml:id="domRetrieveChildren"> @@ -239,13 +266,14 @@ public interface Node { // Node Types <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/domtree.fig" scale="65" /> + <imagedata fileref="Ref/Fig/domtree.fig" scale="65"/> </imageobject> </mediaobject> </figure> <figure xml:id="sda1_dom_nodeTypes"> - <title><classname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html">org.w3c.dom.Node</classname> + <title><classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Node.html">org.w3c.dom.Node</classname> subtypes</title> <itemizedlist> @@ -262,7 +290,8 @@ public interface Node { // Node Types </listitem> <listitem> - <para>Processing instruction: <code language="xml"><?xml-stylesheet type="text/xsl" + <para>Processing instruction: <code + language="xml"><?xml-stylesheet type="text/xsl" href="style.xsl"?></code>.</para> </listitem> @@ -277,44 +306,48 @@ public interface Node { // Node Types </figure> <figure xml:id="domJavaNodeInterfaces"> - <title><xref linkend="glo_DOM" /> <xref linkend="glo_Java" /> binding + <title><xref linkend="glo_DOM"/> <xref linkend="glo_Java"/> binding inheritance interface hierarchy</title> <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/nodeHierarchy.svg" /> + <imagedata fileref="Ref/Fig/nodeHierarchy.svg"/> </imageobject> </mediaobject> </figure> - <para>Current <xref linkend="glo_Java" /> distributions do contain a <xref linkend="glo_DOM" /> implementation including parsers, XPath engines etc. + <para>Current <xref linkend="glo_Java"/> distributions do contain a <xref + linkend="glo_DOM"/> implementation including parsers, XPath engines etc. .</para> - <para>The <xref linkend="glo_DOM" />'s specification defines a (still - growing) set of<link xlink:href="https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/introduction.html#DOMArchitecture-h2"> + <para>The <xref linkend="glo_DOM"/>'s specification defines a (still + growing) set of<link + xlink:href="https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/introduction.html#DOMArchitecture-h2"> modules</link>. An implementation may not implement all of these:</para> <figure xml:id="figureDomModules"> - <title><xref linkend="glo_DOM" /> modules.</title> + <title><xref linkend="glo_DOM"/> modules.</title> <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/dom-architecture.screen.png" /> + <imagedata fileref="Ref/Fig/dom-architecture.screen.png"/> </imageobject> </mediaobject> </figure> <figure xml:id="sda1_dom_fig_jDomVsDomAdvantges"> - <title><xref linkend="glo_Jdom" /> vs. <xref linkend="glo_DOM" />: + <title><xref linkend="glo_Jdom"/> vs. <xref linkend="glo_DOM"/>: Advantages</title> <itemizedlist> <listitem> - <para>Alternative to <orgname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/package-frame.html">org.w3c.dom</orgname>.</para> + <para>Alternative to <orgname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/package-frame.html">org.w3c.dom</orgname>.</para> </listitem> <listitem> - <para>More Java compatible <abbrev>i.e.</abbrev> using <link xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Collection.html">native + <para>More Java compatible <abbrev>i.e.</abbrev> using <link + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Collection.html">native collection interfaces</link></para> </listitem> @@ -326,7 +359,7 @@ public interface Node { // Node Types </figure> <figure xml:id="sda1_dom_fig_jDomVsDomDiadvantages"> - <title><xref linkend="glo_Jdom" /> vs. <xref linkend="glo_DOM" />: + <title><xref linkend="glo_Jdom"/> vs. <xref linkend="glo_DOM"/>: Disadvantages</title> <itemizedlist> @@ -343,7 +376,7 @@ public interface Node { // Node Types </listitem> <listitem> - <para>Potential 3-rd party <xref linkend="glo_DOM" /> framework + <para>Potential 3-rd party <xref linkend="glo_DOM"/> framework incompatibilities.</para> </listitem> </itemizedlist> @@ -351,13 +384,14 @@ public interface Node { // Node Types </section> <section xml:id="domCreate"> - <title>Creating a new <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Document.html">Document</classname> + <title>Creating a new <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Document.html">Document</classname> instance from scratch</title> <titleabbrev>New document</titleabbrev> - <para>This lecture's exercises are based on <xref linkend="glo_Jdom" /> in - favour of a <quote>real</quote> Java <xref linkend="glo_DOM" /> language + <para>This lecture's exercises are based on <xref linkend="glo_Jdom"/> in + favour of a <quote>real</quote> Java <xref linkend="glo_DOM"/> language binding implementation.</para> <figure xml:id="sda1_fig_jdomMavenConfig"> @@ -365,7 +399,8 @@ public interface Node { // Node Types <programlisting language="xml"><dependency> <groupId>org.jdom</groupId> - <artifactId><link xlink:href="https://mvnrepository.com/artifact/org.jdom/jdom2">jdom2</link></artifactId> + <artifactId><link + xlink:href="https://mvnrepository.com/artifact/org.jdom/jdom2">jdom2</link></artifactId> <version>2.0.6</version> </dependency> ...</programlisting> @@ -378,27 +413,35 @@ public interface Node { // Node Types <title>Exporting data as XML</title> <calloutlist> - <callout arearefs="sda1_dom_createXmlFromScratch-1-co" xml:id="sda1_dom_createXmlFromScratch-1"> - <para>Create an empty <link xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html">Element</link> + <callout arearefs="sda1_dom_createXmlFromScratch-1-co" + xml:id="sda1_dom_createXmlFromScratch-1"> + <para>Create an empty <link + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html">Element</link> instance to become the document's root.</para> </callout> - <callout arearefs="sda1_dom_createXmlFromScratch-2-co" xml:id="sda1_dom_createXmlFromScratch-2"> - <para>Add a <classname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Text.html">Text</classname> + <callout arearefs="sda1_dom_createXmlFromScratch-2-co" + xml:id="sda1_dom_createXmlFromScratch-2"> + <para>Add a <classname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Text.html">Text</classname> node.</para> </callout> - <callout arearefs="sda1_dom_createXmlFromScratch-3-co" xml:id="sda1_dom_createXmlFromScratch-3"> + <callout arearefs="sda1_dom_createXmlFromScratch-3-co" + xml:id="sda1_dom_createXmlFromScratch-3"> <para>Set a new attribute <code language="xml">date</code> to value <quote>23.02.2000</quote>.</para> </callout> - <callout arearefs="sda1_dom_createXmlFromScratch-4-co" xml:id="sda1_dom_createXmlFromScratch-4"> - <para>Create a serializer instance of <classname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html">XMLOutputter</classname> + <callout arearefs="sda1_dom_createXmlFromScratch-4-co" + xml:id="sda1_dom_createXmlFromScratch-4"> + <para>Create a serializer instance of <classname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html">XMLOutputter</classname> providing output prettifying.</para> </callout> - <callout arearefs="sda1_dom_createXmlFromScratch-5-co" xml:id="sda1_dom_createXmlFromScratch-5"> + <callout arearefs="sda1_dom_createXmlFromScratch-5-co" + xml:id="sda1_dom_createXmlFromScratch-5"> <para>Serialize the result tree to a stream.</para> </callout> </calloutlist> @@ -407,20 +450,34 @@ public interface Node { // Node Types <para>The subsequent code illustrates these steps:</para> <figure xml:id="sda1_dom_createXmlFromScratch"> - <title><xref linkend="glo_XML" /> document creation from scratch.</title> + <title><xref linkend="glo_XML"/> document creation from scratch.</title> - <programlisting language="java"><link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/Doc/Sda1/Ref/Jdom/P/CreateScratch/src/main/java/de/hdm_stuttgart/mi/sda1/jdom/CreateDoc.java">final Element titel</link> = new Element("titel"); <co linkends="sda1_dom_createXmlFromScratch-1" xml:id="sda1_dom_createXmlFromScratch-1-co" /> + <programlisting language="java"><link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/Doc/Sda1/Ref/Jdom/P/CreateScratch/src/main/java/de/hdm_stuttgart/mi/sda1/jdom/CreateDoc.java">final Element titel</link> = new Element("titel"); <co + linkends="sda1_dom_createXmlFromScratch-1" + xml:id="sda1_dom_createXmlFromScratch-1-co"/> -titel.addContent(new Text("First try")); <co linkends="sda1_dom_createXmlFromScratch-2" xml:id="sda1_dom_createXmlFromScratch-2-co" /> +titel.addContent(new Text("First try")); <co + linkends="sda1_dom_createXmlFromScratch-2" + xml:id="sda1_dom_createXmlFromScratch-2-co"/> -titel.setAttribute("date", "23.02.2000"); <co linkends="sda1_dom_createXmlFromScratch-3" xml:id="sda1_dom_createXmlFromScratch-3-co" /> +titel.setAttribute("date", "23.02.2000"); <co + linkends="sda1_dom_createXmlFromScratch-3" + xml:id="sda1_dom_createXmlFromScratch-3-co"/> final XMLOutputter printer = - new XMLOutputter(Format.getPrettyFormat());<co linkends="sda1_dom_createXmlFromScratch-4" xml:id="sda1_dom_createXmlFromScratch-4-co" /> - -printer.output(titel, System.out); <co linkends="sda1_dom_createXmlFromScratch-5" xml:id="sda1_dom_createXmlFromScratch-5-co" /></programlisting> - - <screen language="xml">Result: <titel <coref linkend="sda1_dom_createXmlFromScratch-1-co" /> date="23.02.2000"<coref linkend="sda1_dom_createXmlFromScratch-3-co" />>First try<coref linkend="sda1_dom_createXmlFromScratch-2-co" /></titel></screen> + new XMLOutputter(Format.getPrettyFormat());<co + linkends="sda1_dom_createXmlFromScratch-4" + xml:id="sda1_dom_createXmlFromScratch-4-co"/> + +printer.output(titel, System.out); <co + linkends="sda1_dom_createXmlFromScratch-5" + xml:id="sda1_dom_createXmlFromScratch-5-co"/></programlisting> + + <screen language="xml">Result: <titel <coref + linkend="sda1_dom_createXmlFromScratch-1-co"/> date="23.02.2000"<coref + linkend="sda1_dom_createXmlFromScratch-3-co"/>>First try<coref + linkend="sda1_dom_createXmlFromScratch-2-co"/></titel></screen> </figure> </section> @@ -435,12 +492,15 @@ printer.output(titel, System.out); <co linkends="sda1_dom_createXmlFromScratch-5 <question> <label>Creation of an extended XML document instance</label> - <para>In order to run the examples the <filename xlink:href="http://www.jdom.org/downloads">jdom2</filename> + <para>In order to run the examples the <filename + xlink:href="http://www.jdom.org/downloads">jdom2</filename> library must be configured in your project's <filename>pom.xml</filename>.</para> - <para>The <xref linkend="glo_DOM" /> creating example given before - may be used as a starting point. Extend the <xref linkend="glo_DOM" /> tree created in <xref linkend="sda1_dom_createXmlFromScratch" /> to produce an extended + <para>The <xref linkend="glo_DOM"/> creating example given before + may be used as a starting point. Extend the <xref + linkend="glo_DOM"/> tree created in <xref + linkend="sda1_dom_createXmlFromScratch"/> to produce an extended XML document:</para> <programlisting language="xml"><title> @@ -464,14 +524,16 @@ printer.output(titel, System.out); <co linkends="sda1_dom_createXmlFromScratch-5 <titleabbrev>Parsing</titleabbrev> - <para>JDom uses <acronym xlink:href="http://www.saxproject.org">SAX</acronym> for parsing XML - documents. Rather than handling <acronym xlink:href="http://www.saxproject.org">SAX</acronym> events ourselves we - prefer a <xref linkend="glo_DOM" /> (in memory) representation of our + <para>JDom uses <acronym + xlink:href="http://www.saxproject.org">SAX</acronym> for parsing XML + documents. Rather than handling <acronym + xlink:href="http://www.saxproject.org">SAX</acronym> events ourselves we + prefer a <xref linkend="glo_DOM"/> (in memory) representation of our document. The <link linkend="simpleCatalog">simple catalog</link> serves as an introductory example:</para> <figure xml:id="sda1_dom_catalogSampleData"> - <title><xref linkend="glo_XML" /> catalog sample data</title> + <title><xref linkend="glo_XML"/> catalog sample data</title> <programlisting language="xml"><catalog> <item orderNo="3218">Swinging headset</item> @@ -479,92 +541,136 @@ printer.output(titel, System.out); <co linkends="sda1_dom_createXmlFromScratch-5 </catalog></programlisting> </figure> - <para>We already noticed the need for an <classname xlink:href="http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> - instance during <acronym xlink:href="http://www.saxproject.org">SAX</acronym> processing. A <xref linkend="glo_DOM" /> Parser requires a means to communicate parsing errors - in case of <xref linkend="glo_XML" /> related errors. A <xref linkend="glo_DOM" /> parser implementor is free to choose his + <para>We already noticed the need for an <classname + xlink:href="http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> + instance during <acronym + xlink:href="http://www.saxproject.org">SAX</acronym> processing. A <xref + linkend="glo_DOM"/> Parser requires a means to communicate parsing errors + in case of <xref linkend="glo_XML"/> related errors. A <xref + linkend="glo_DOM"/> parser implementor is free to choose his implementation but most implementations are based on top of a so called <acronym xlink:href="http://www.saxproject.org">SAX</acronym> parser. The <acronym xlink:href="http://www.saxproject.org">SAX</acronym> parser in - turn defines a standard <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> + turn defines a standard <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> interface we may use for the sake of conveying parsing errors:</para> <figure xml:id="sda1_dom_saxErrorHandler"> - <title><xref linkend="glo_SAX" /> error handler</title> + <title><xref linkend="glo_SAX"/> error handler</title> - <programlisting language="java">public class <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/sax/MySaxErrorHandler.java">MySaxErrorHandler</link> implements <link xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</link> { + <programlisting language="java">public class <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/sax/MySaxErrorHandler.java">MySaxErrorHandler</link> implements <link + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</link> { - private PrintStream out; <co linkends="sda1_dom_saxErrorHandler-1" xml:id="sda1_dom_saxErrorHandler-1-co" />//The error handler's output goes here + private PrintStream out; <co linkends="sda1_dom_saxErrorHandler-1" + xml:id="sda1_dom_saxErrorHandler-1-co"/>//The error handler's output goes here - private String getParseExceptionInfo <co linkends="sda1_dom_saxErrorHandler-2" xml:id="sda1_dom_saxErrorHandler-2-co" />(SAXParseException ex) { + private String getParseExceptionInfo <co + linkends="sda1_dom_saxErrorHandler-2" + xml:id="sda1_dom_saxErrorHandler-2-co"/>(SAXParseException ex) { return "Error '" + ex.getMessage() + "' at line " + ex.getLineNumber() + ", column " + ex.getColumnNumber(); } - public MySaxErrorHandler(final PrintStream out <co linkends="sda1_dom_saxErrorHandler-3" xml:id="sda1_dom_saxErrorHandler-3-co" />) {this.out = out;} - @Override public void warning<co linkends="sda1_dom_saxErrorHandler-4" xml:id="sda1_dom_saxErrorHandler-4-co" /> (SAXParseException exception <co linkends="sda1_dom_saxErrorHandler-5" xml:id="sda1_dom_saxErrorHandler-5-co" />) throws SAXException { + public MySaxErrorHandler(final PrintStream out <co + linkends="sda1_dom_saxErrorHandler-3" + xml:id="sda1_dom_saxErrorHandler-3-co"/>) {this.out = out;} + @Override public void warning<co linkends="sda1_dom_saxErrorHandler-4" + xml:id="sda1_dom_saxErrorHandler-4-co"/> (SAXParseException exception <co + linkends="sda1_dom_saxErrorHandler-5" + xml:id="sda1_dom_saxErrorHandler-5-co"/>) throws SAXException { out.print("Warning:" + getParseExceptionInfo(exception)); } - @Override public void error <co linkends="sda1_dom_saxErrorHandler-6" xml:id="sda1_dom_saxErrorHandler-6-co" />(SAXParseException exception <coref linkend="sda1_dom_saxErrorHandler-3-co" />) throws SAXException { + @Override public void error <co linkends="sda1_dom_saxErrorHandler-6" + xml:id="sda1_dom_saxErrorHandler-6-co"/>(SAXParseException exception <coref + linkend="sda1_dom_saxErrorHandler-3-co"/>) throws SAXException { out.print("Error:" + getParseExceptionInfo(exception)); } @Override - public void fatalError <co linkends="sda1_dom_saxErrorHandler-7" xml:id="sda1_dom_saxErrorHandler-7-co" />(SAXParseException exception <coref linkend="sda1_dom_saxErrorHandler-3-co" />) throws SAXException { + public void fatalError <co linkends="sda1_dom_saxErrorHandler-7" + xml:id="sda1_dom_saxErrorHandler-7-co"/>(SAXParseException exception <coref + linkend="sda1_dom_saxErrorHandler-3-co"/>) throws SAXException { out.print("Fatal error:" + getParseExceptionInfo(exception)); } }</programlisting> </figure> <calloutlist> - <callout arearefs="sda1_dom_saxErrorHandler-1-co" xml:id="sda1_dom_saxErrorHandler-1"> + <callout arearefs="sda1_dom_saxErrorHandler-1-co" + xml:id="sda1_dom_saxErrorHandler-1"> <para>Error and warning messages go here. The underlying stream may be linked <abbrev>e.g.</abbrev> to a file or to standard output.</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-2-co" xml:id="sda1_dom_saxErrorHandler-2"> + <callout arearefs="sda1_dom_saxErrorHandler-2-co" + xml:id="sda1_dom_saxErrorHandler-2"> <para>Internal method assembling the actual error or warning message containing a line number / column number based file reference.</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-3-co" xml:id="sda1_dom_saxErrorHandler-3"> + <callout arearefs="sda1_dom_saxErrorHandler-3-co" + xml:id="sda1_dom_saxErrorHandler-3"> <para>Constructor for defining the respective stream.</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-4-co" xml:id="sda1_dom_saxErrorHandler-4"> + <callout arearefs="sda1_dom_saxErrorHandler-4-co" + xml:id="sda1_dom_saxErrorHandler-4"> <para>Callback method being called in case of minor problems i.e. a missing mandatory attribute.</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-5-co" xml:id="sda1_dom_saxErrorHandler-5"> + <callout arearefs="sda1_dom_saxErrorHandler-5-co" + xml:id="sda1_dom_saxErrorHandler-5"> <para>The exception instance holding a detailed problem description</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-6-co" xml:id="sda1_dom_saxErrorHandler-6"> + <callout arearefs="sda1_dom_saxErrorHandler-6-co" + xml:id="sda1_dom_saxErrorHandler-6"> <para>Severe error.</para> </callout> - <callout arearefs="sda1_dom_saxErrorHandler-7-co" xml:id="sda1_dom_saxErrorHandler-7"> + <callout arearefs="sda1_dom_saxErrorHandler-7-co" + xml:id="sda1_dom_saxErrorHandler-7"> <para>Fatal error <abbrev>e.g.</abbrev> indicating improper nesting of - elements prohibiting further parsing of the given <xref linkend="glo_XML" /> input.</para> + elements prohibiting further parsing of the given <xref + linkend="glo_XML"/> input.</para> </callout> </calloutlist> - <para>We use this bit to assemble a <xref linkend="glo_DOM" /> based <xref linkend="glo_XML" /> parsing application:.</para> + <para>We use this bit to assemble a <xref linkend="glo_DOM"/> based <xref + linkend="glo_XML"/> parsing application:.</para> <figure xml:id="sda1_dom_fig_TreeTraversal"> - <title>Accessing an XML Tree purely by <xref linkend="glo_DOM" /> + <title>Accessing an XML Tree purely by <xref linkend="glo_DOM"/> methods.</title> - <programlisting language="java">public class <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/dom/ReadCatalog.java">ReadCatalog</link> { - private SAXBuilder builder = new SAXBuilder(); <co linkends="sda1_dom_fig_TreeTraversal-1.2" xml:id="sda1_dom_fig_TreeTraversal-1.2-co" /> + <programlisting language="java">public class <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/dom/ReadCatalog.java">ReadCatalog</link> { + private SAXBuilder builder = new SAXBuilder(); <co + linkends="sda1_dom_fig_TreeTraversal-1.2" + xml:id="sda1_dom_fig_TreeTraversal-1.2-co"/> public ReadCatalog() { - builder.setErrorHandler(new <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/sax/MySaxErrorHandler.java">MySaxErrorHandler</link>(System.out)); <co linkends="sda1_dom_fig_TreeTraversal-2.2" xml:id="sda1_dom_fig_TreeTraversal-2.2-co" /> + builder.setErrorHandler(new <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/sax/MySaxErrorHandler.java">MySaxErrorHandler</link>(System.out)); <co + linkends="sda1_dom_fig_TreeTraversal-2.2" + xml:id="sda1_dom_fig_TreeTraversal-2.2-co"/> } - public void process(final String filename) <co linkends="sda1_dom_fig_TreeTraversal-3.2" xml:id="sda1_dom_fig_TreeTraversal-3.2-co" /> throws JDOMException <co linkends="sda1_dom_fig_TreeTraversal-4.2" xml:id="sda1_dom_fig_TreeTraversal-4.2-co" />, IOException { + public void process(final String filename) <co + linkends="sda1_dom_fig_TreeTraversal-3.2" + xml:id="sda1_dom_fig_TreeTraversal-3.2-co"/> throws JDOMException <co + linkends="sda1_dom_fig_TreeTraversal-4.2" + xml:id="sda1_dom_fig_TreeTraversal-4.2-co"/>, IOException { final Document docInput = builder.build( - getClass().getClassLoader().getResource(filename) <co linkends="sda1_dom_fig_TreeTraversal-5.2" xml:id="sda1_dom_fig_TreeTraversal-5.2-co" /> + getClass().getClassLoader().getResource(filename) <co + linkends="sda1_dom_fig_TreeTraversal-5.2" + xml:id="sda1_dom_fig_TreeTraversal-5.2-co"/> ); - final Element docRoot = docInput.getRootElement(); <co linkends="sda1_dom_fig_TreeTraversal-6.2" xml:id="sda1_dom_fig_TreeTraversal-6.2-co" /> - docRoot.getChildren().forEach(item -> <co linkends="sda1_dom_fig_TreeTraversal-7" xml:id="sda1_dom_fig_TreeTraversal-7-co" /> + final Element docRoot = docInput.getRootElement(); <co + linkends="sda1_dom_fig_TreeTraversal-6.2" + xml:id="sda1_dom_fig_TreeTraversal-6.2-co"/> + docRoot.getChildren().forEach(item -> <co + linkends="sda1_dom_fig_TreeTraversal-7" + xml:id="sda1_dom_fig_TreeTraversal-7-co"/> System.out.println( "Article: " + item.getText() + ", order number: " + item.getAttributeValue("orderNo"))); @@ -573,48 +679,58 @@ printer.output(titel, System.out); <co linkends="sda1_dom_createXmlFromScratch-5 </figure> <calloutlist> - <callout arearefs="sda1_dom_fig_TreeTraversal-1.2-co" xml:id="sda1_dom_fig_TreeTraversal-1.2"> + <callout arearefs="sda1_dom_fig_TreeTraversal-1.2-co" + xml:id="sda1_dom_fig_TreeTraversal-1.2"> <para>The parser workhorse.</para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-2.2-co" xml:id="sda1_dom_fig_TreeTraversal-2.2"> - <para>Though an <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> + <callout arearefs="sda1_dom_fig_TreeTraversal-2.2-co" + xml:id="sda1_dom_fig_TreeTraversal-2.2"> + <para>Though an <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/xml/sax/ErrorHandler.html">ErrorHandler</classname> is not strictly being required it allows for localization of XML document parsing errors and warnings.</para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-3.2-co" xml:id="sda1_dom_fig_TreeTraversal-3.2"> + <callout arearefs="sda1_dom_fig_TreeTraversal-3.2-co" + xml:id="sda1_dom_fig_TreeTraversal-3.2"> <para>Descending a catalog till its <tag class="starttag">item</tag> elements. For each <tag class="starttag">item</tag> its name and order number are being written to the output.</para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-4.2-co" xml:id="sda1_dom_fig_TreeTraversal-4.2"> + <callout arearefs="sda1_dom_fig_TreeTraversal-4.2-co" + xml:id="sda1_dom_fig_TreeTraversal-4.2"> <para>Parsing error being thrown in <abbrev>i.e.</abbrev> case of non- wellformed catalog documents.</para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-5.2-co" xml:id="sda1_dom_fig_TreeTraversal-5.2"> + <callout arearefs="sda1_dom_fig_TreeTraversal-5.2-co" + xml:id="sda1_dom_fig_TreeTraversal-5.2"> <para>Parsing XML input file relative to the project's <filename>src/main/resources</filename> folder.</para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-6.2-co" xml:id="sda1_dom_fig_TreeTraversal-6.2"> + <callout arearefs="sda1_dom_fig_TreeTraversal-6.2-co" + xml:id="sda1_dom_fig_TreeTraversal-6.2"> <para>Accessing the document's root element <catalog></para> </callout> - <callout arearefs="sda1_dom_fig_TreeTraversal-7-co" xml:id="sda1_dom_fig_TreeTraversal-7"> - <para>Streaming all <tag class="starttag">item</tag> children of <tag class="starttag">catalog</tag>.</para> + <callout arearefs="sda1_dom_fig_TreeTraversal-7-co" + xml:id="sda1_dom_fig_TreeTraversal-7"> + <para>Streaming all <tag class="starttag">item</tag> children of <tag + class="starttag">catalog</tag>.</para> </callout> </calloutlist> <para>Execution of <methodname>process(...)</methodname> requires a driver - instance providing an <xref linkend="glo_XML" /> input filename:</para> + instance providing an <xref linkend="glo_XML"/> input filename:</para> <figure xml:id="sda1_dom_fig_readCatalogDriver"> <title>Driver class execution entry point</title> - <programlisting language="java">public class <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/dom/ReadCatalogDriver.java">ReadCatalogDriver</link> { + <programlisting language="java">public class <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/Jdom/Catalog/src/main/java/dom/ReadCatalogDriver.java">ReadCatalogDriver</link> { public static void main(String[] argv) throws Exception { final ReadCatalog catalogReader = new ReadCatalog(); @@ -629,12 +745,13 @@ Article: 200W Stereo Amplifier, order number: 9921</screen> <figure xml:id="sda1_dom_fig_readCatalogSampleProject"> <title>Project sample code for import</title> - <para><uri xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/Jdom/Catalog">https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/Jdom/Catalog</uri></para> + <para><uri + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/Jdom/Catalog">https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/Jdom/Catalog</uri></para> </figure> </section> <section xml:id="sda1SimpleDomProcess"> - <title>Simple <xref linkend="glo_DOM" /> processing</title> + <title>Simple <xref linkend="glo_DOM"/> processing</title> <section xml:id="sda1SectElementVisualize"> <title>Visualizing XML document elements</title> @@ -667,8 +784,9 @@ Article: 200W Stereo Amplifier, order number: 9921</screen> </content> </memo></programlisting> - <para>Write a <xref linkend="glo_Java" /> application which lists - all elements by <link xlink:href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order">depth + <para>Write a <xref linkend="glo_Java"/> application which lists + all elements by <link + xlink:href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order">depth first pre order</link> traversal among with their respective nesting depth and attributes.</para> @@ -706,21 +824,26 @@ Document contains 15 elements and 3 attributes.</screen> </section> <section xml:id="sda1SectFunctionalBasics"> - <title>Reminder to functional programming elements in <xref linkend="glo_Java" />.</title> + <title>Reminder to functional programming elements in <xref + linkend="glo_Java"/>.</title> <qandaset defaultlabel="qanda" xml:id="sda1QandaFunctionalBasics"> <qandadiv> <qandaentry> <question> <para>As a courtesy we remind all participants to functional - programming elements being dealt with in <link xlink:href="https://www.hdm-stuttgart.de/studierende/stundenplan/vorlesungsverzeichnis/vorlesung_detail?vorlid=5211589" xml:lang="de">Softwareentwicklung 2</link>.</para> + programming elements being dealt with in <link + xlink:href="https://www.hdm-stuttgart.de/studierende/stundenplan/vorlesungsverzeichnis/vorlesung_detail?vorlid=5211589" + xml:lang="de">Softwareentwicklung 2</link>.</para> - <para>This exercise has been derived from <link xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda + <para>This exercise has been derived from <link + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda Expressions - The Java™ Tutorials</link>. Depending on your own personal knowledge you may want to start that trail beforehand.</para> - <para>Import the following project template into <xref linkend="glo_Soft_IntellijIDEA" />:</para> + <para>Import the following project template into <xref + linkend="glo_Soft_IntellijIDEA"/>:</para> <annotation role="make"> <para role="eclipse">Sda1/Streams/Template</para> @@ -732,7 +855,8 @@ Document contains 15 elements and 3 attributes.</screen> <listitem> <para>Some boilerplate code in <classname>de.hdm_stuttgart.mi.javastreams.RosterTest</classname> - modified from <link xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda + modified from <link + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda Expressions - The Java™ Tutorials</link>. Execution does make sense when reading Oracle's trail in parallel.</para> </listitem> @@ -740,7 +864,8 @@ Document contains 15 elements and 3 attributes.</screen> <listitem> <para>A unit test class <classname>de.hdm_stuttgart.mi.javastreams.Java8FunctionalTest</classname> - currently being masked by an <interfacename xlink:href="http://junit.sourceforge.net/javadoc/org/junit/Ignore.html">@Ignore</interfacename> + currently being masked by an <interfacename + xlink:href="http://junit.sourceforge.net/javadoc/org/junit/Ignore.html">@Ignore</interfacename> annotation to be removed for enabling tests. This is your place to actually start working.</para> </listitem> @@ -763,23 +888,31 @@ Document contains 15 elements and 3 attributes.</screen> <classname>de.hdm_stuttgart.mi.javastreams.Java8FunctionalTest</classname> is intended to serve as a blueprint:</para> - <programlisting language="java"> /** - * Order all male students by email and create a List<String> of their respective - * names in that order eliminating possible duplicates: <co linkends="sda1CalloutFunctionalJunit-1" xml:id="sda1CalloutFunctionalJunit-1-co" /> - * - * "Bob", 2, Student.Sex.MALE, "bob@uk.edu" <co linkends="sda1CalloutFunctionalJunit-2" xml:id="sda1CalloutFunctionalJunit-2-co" /> - * "Fred", 2, Student.Sex.MALE, "fred@example.com" - * "George", 4, Student.Sex.MALE, "george@math.edu" - * "Jane", 1, Student.Sex.FEMALE, "jane@kiv.de" - * "Kim", 2, Student.Sex.FEMALE, "wilde@serious.de" - * - * ==> {"Bob", "Fred", "George"} <co linkends="sda1CalloutFunctionalJunit-3" xml:id="sda1CalloutFunctionalJunit-3-co" /> - * - */ - @Test - public void allMaleDistinctNameOrderedByEmail() { - - List<String> emails = <co linkends="sda1CalloutFunctionalJunit-4" xml:id="sda1CalloutFunctionalJunit-4-co" /> + <programlisting language="java">/** + * Order all male students by email and create a List<String> of their respective + * names in that order eliminating possible duplicates: <co + linkends="sda1CalloutFunctionalJunit-1" + xml:id="sda1CalloutFunctionalJunit-1-co"/> + * + * "Bob", 2, Student.Sex.MALE, "bob@uk.edu" <co + linkends="sda1CalloutFunctionalJunit-2" + xml:id="sda1CalloutFunctionalJunit-2-co"/> + * "Fred", 2, Student.Sex.MALE, "fred@example.com" + * "George", 4, Student.Sex.MALE, "george@math.edu" + * "Jane", 1, Student.Sex.FEMALE, "jane@kiv.de" + * "Kim", 2, Student.Sex.FEMALE, "wilde@serious.de" + * + * ==> {"Bob", "Fred", "George"} <co + linkends="sda1CalloutFunctionalJunit-3" + xml:id="sda1CalloutFunctionalJunit-3-co"/> + * + */ +@Test +public void allMaleDistinctNameOrderedByEmail() { + + final List<String> emails = <co + linkends="sda1CalloutFunctionalJunit-4" + xml:id="sda1CalloutFunctionalJunit-4-co"/> roster. stream(). filter(s -> s.gender == Sex.MALE). @@ -788,32 +921,38 @@ Document contains 15 elements and 3 attributes.</screen> distinct(). collect(Collectors.toList()); - assertThat(emails, <co linkends="sda1CalloutFunctionalJunit-5" xml:id="sda1CalloutFunctionalJunit-5-co" /> - Matchers.<List<String>> equalTo( + assertThat(emails, <co linkends="sda1CalloutFunctionalJunit-5" + xml:id="sda1CalloutFunctionalJunit-5-co"/> + Matchers.<List<String>> equalTo( ImmutableList.of("Bob", "Fred", "George") - ) - ); - }</programlisting> + ) + ); +}</programlisting> <calloutlist> - <callout arearefs="sda1CalloutFunctionalJunit-1-co" xml:id="sda1CalloutFunctionalJunit-1"> + <callout arearefs="sda1CalloutFunctionalJunit-1-co" + xml:id="sda1CalloutFunctionalJunit-1"> <para>An informal description of the desired outcome.</para> </callout> - <callout arearefs="sda1CalloutFunctionalJunit-2-co" xml:id="sda1CalloutFunctionalJunit-2"> + <callout arearefs="sda1CalloutFunctionalJunit-2-co" + xml:id="sda1CalloutFunctionalJunit-2"> <para>A list of records illustrating a processing step.</para> </callout> - <callout arearefs="sda1CalloutFunctionalJunit-3-co" xml:id="sda1CalloutFunctionalJunit-3"> + <callout arearefs="sda1CalloutFunctionalJunit-3-co" + xml:id="sda1CalloutFunctionalJunit-3"> <para>An informal description of the desired output.</para> </callout> - <callout arearefs="sda1CalloutFunctionalJunit-4-co" xml:id="sda1CalloutFunctionalJunit-4"> + <callout arearefs="sda1CalloutFunctionalJunit-4-co" + xml:id="sda1CalloutFunctionalJunit-4"> <para>A stream pipeline yielding the result.</para> </callout> - <callout arearefs="sda1CalloutFunctionalJunit-5-co" xml:id="sda1CalloutFunctionalJunit-5"> + <callout arearefs="sda1CalloutFunctionalJunit-5-co" + xml:id="sda1CalloutFunctionalJunit-5"> <para>A unit test checking for correctness.</para> </callout> </calloutlist> @@ -823,21 +962,31 @@ Document contains 15 elements and 3 attributes.</screen> <tip> <para>Unit tests for this type of work frequently require - comparing <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/List.html">List</classname> - and <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Map.html">Map</classname> - objects. The above code <coref linkend="sda1CalloutFunctionalJunit-5-co" /> uses <link xlink:href="https://github.com/google/guava/wiki">Guava</link> - for creating <link xlink:href="https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable + comparing <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/List.html">List</classname> + and <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Map.html">Map</classname> + objects. The above code <coref + linkend="sda1CalloutFunctionalJunit-5-co"/> uses <link + xlink:href="https://github.com/google/guava/wiki">Guava</link> + for creating <link + xlink:href="https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</link> representing expected outcomes.</para> - <para>On the other end <productname xlink:href="http://hamcrest.org/">Hamcrest</productname> - allows for using these collections <link xlink:href="https://github.com/hamcrest/JavaHamcrest/wiki/The-Hamcrest-Tutorial">to + <para>On the other end <productname + xlink:href="http://hamcrest.org/">Hamcrest</productname> + allows for using these collections <link + xlink:href="https://github.com/hamcrest/JavaHamcrest/wiki/The-Hamcrest-Tutorial">to be compared</link> with actual test outcomes. The test <methodname>public void studentNamesBySex()</methodname> - contains a more complex example constructing a <classname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Map.html">Map</classname>.</para> + contains a more complex example constructing a <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Map.html">Map</classname>.</para> <para>Larger numbers of immutable collection items may require - using the <methodname xlink:href="https://google.github.io/guava/releases/25.1-jre/api/docs//com/google/common/collect/ImmutableMap.Builder.html#put-K-V-">put()</methodname> - method being described in the topmost example of <classname xlink:href="https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/ImmutableMap.Builder.html">ImmutableMap.Builder</classname> + using the <methodname + xlink:href="https://google.github.io/guava/releases/25.1-jre/api/docs//com/google/common/collect/ImmutableMap.Builder.html#put-K-V-">put()</methodname> + method being described in the topmost example of <classname + xlink:href="https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/ImmutableMap.Builder.html">ImmutableMap.Builder</classname> rather than merely a constructor.</para> </tip> </question> @@ -859,12 +1008,14 @@ Document contains 15 elements and 3 attributes.</screen> <qandadiv> <qandaentry> <question> - <para>Instead of transforming our <link linkend="simpleCatalog">simple catalog</link> into textual - output in <xref linkend="sda1_dom_fig_TreeTraversal" /> we may - also create <xref linkend="glo_XHTML" /> pages like:</para> + <para>Instead of transforming our <link + linkend="simpleCatalog">simple catalog</link> into textual + output in <xref linkend="sda1_dom_fig_TreeTraversal"/> we may + also create <xref linkend="glo_XHTML"/> pages like:</para> <programlisting language="xml"><!DOCTYPE html> -<!-- Static content section--> <co xml:id="sda1CatalogStaticContentSection" /> +<!-- Static content section--> <co + xml:id="sda1CatalogStaticContentSection"/> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Available articles</title> @@ -876,12 +1027,15 @@ Document contains 15 elements and 3 attributes.</screen> <tr /> <th>Article Description</th> <th>Order Number</th> - <!-- End of static, beginning of dynamic section--> <co xml:id="sda1CatalogDynamicContentSection" /> + <!-- End of static, beginning of dynamic section--> <co + xml:id="sda1CatalogDynamicContentSection"/> <tr> - <td align="left"><emphasis role="bold">Swinging headset</emphasis></td><td><emphasis role="bold">3218</emphasis></td> + <td align="left"><emphasis role="bold">Swinging headset</emphasis></td><td><emphasis + role="bold">3218</emphasis></td> </tr> <tr> - <td align="left"><emphasis role="bold">200W Stereo Amplifier</emphasis></td><td><emphasis role="bold">9921</emphasis></td> + <td align="left"><emphasis role="bold">200W Stereo Amplifier</emphasis></td><td><emphasis + role="bold">9921</emphasis></td> </tr> </tbody> </table> @@ -891,19 +1045,29 @@ Document contains 15 elements and 3 attributes.</screen> <para>Rather then just coding<code>...println(<html>\n\t<head>...)</code> statements you are expected to implement a more sophisticated - solution: We may combine <xref linkend="sda1_dom_fig_TreeTraversal" /> and <xref linkend="createDocModify" />. The idea is parsing the <link linkend="simpleCatalog">XML catalog instance</link> to a <xref linkend="glo_Java" /> <xref linkend="glo_DOM" /> object as before. - Then construct a <emphasis>second</emphasis> <xref linkend="glo_DOM" /> tree representing the desired HTML output - and fill in the article information from the first <xref linkend="glo_DOM" /> tree accordingly.</para> + solution: We may combine <xref + linkend="sda1_dom_fig_TreeTraversal"/> and <xref + linkend="createDocModify"/>. The idea is parsing the <link + linkend="simpleCatalog">XML catalog instance</link> to a <xref + linkend="glo_Java"/> <xref linkend="glo_DOM"/> object as before. + Then construct a <emphasis>second</emphasis> <xref + linkend="glo_DOM"/> tree representing the desired HTML output + and fill in the article information from the first <xref + linkend="glo_DOM"/> tree accordingly.</para> <tip> - <para>The desired <xref linkend="glo_HTML" /> output does - contain both static <coref linkend="sda1CatalogStaticContentSection" /> and dynamic - content <coref linkend="sda1CatalogDynamicContentSection" /> - with respect to a given <xref linkend="glo_XML" /> <link linkend="simpleCatalog">catalog input</link>.</para> - - <para>The static content may be implemented as in <xref linkend="sda1_dom_createXmlFromScratch" />. Regarding dynamic - content you'll have to parse your <link linkend="simpleCatalog">catalog input</link> and construct the - <xref linkend="glo_HTML" />'s table lines in a similar fashion + <para>The desired <xref linkend="glo_HTML"/> output does + contain both static <coref + linkend="sda1CatalogStaticContentSection"/> and dynamic + content <coref linkend="sda1CatalogDynamicContentSection"/> + with respect to a given <xref linkend="glo_XML"/> <link + linkend="simpleCatalog">catalog input</link>.</para> + + <para>The static content may be implemented as in <xref + linkend="sda1_dom_createXmlFromScratch"/>. Regarding dynamic + content you'll have to parse your <link + linkend="simpleCatalog">catalog input</link> and construct the + <xref linkend="glo_HTML"/>'s table lines in a similar fashion by iterating over <code><item orderNo="...">...</item></code> elements .</para> </tip> @@ -942,7 +1106,9 @@ public class HtmlTree { * e.g. {"Article Description", "Order Number" } */ public HtmlTree(final String titleText, - final String[] tableHeaderFields) { <co linkends="programlisting_catalog2html_htmlskel_co" xml:id="programlisting_catalog2html_htmlskel" /> + final String[] tableHeaderFields) { <co + linkends="programlisting_catalog2html_htmlskel_co" + xml:id="programlisting_catalog2html_htmlskel"/> final DocType doctype = new DocType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", @@ -985,7 +1151,9 @@ public class HtmlTree { * @param itemName The item's name (e.g. Tennis racket) * @param orderNo The item's order number */ - public void appendItem(final String itemName, final String orderNo) { <co linkends="programlisting_catalog2html_insertproduct_co" xml:id="programlisting_catalog2html_insertproduct" /> + public void appendItem(final String itemName, final String orderNo) { <co + linkends="programlisting_catalog2html_insertproduct_co" + xml:id="programlisting_catalog2html_insertproduct"/> final Element tr = new Element("tr"); tableBody.addContent(tr); tr.addContent(new Element("td").addContent(new Text(itemName))); @@ -1018,7 +1186,8 @@ public class HtmlTree { }</programlisting> <calloutlist> - <callout arearefs="programlisting_catalog2html_htmlskel" xml:id="programlisting_catalog2html_htmlskel_co"> + <callout arearefs="programlisting_catalog2html_htmlskel" + xml:id="programlisting_catalog2html_htmlskel_co"> <para>A basic HTML skeleton is is being created:</para> <programlisting language="xml"><?xml version="1.0" encoding="UTF-8"?> @@ -1044,22 +1213,24 @@ public class HtmlTree { this point and thus invalid.</para> </callout> - <callout arearefs="programlisting_catalog2html_insertproduct" xml:id="programlisting_catalog2html_insertproduct_co"> + <callout arearefs="programlisting_catalog2html_insertproduct" + xml:id="programlisting_catalog2html_insertproduct_co"> <para>Calling <methodname>solve.dom.HtmlTree.appendItem(String,String)</methodname> once per <tag class="starttag">item</tag> completes the creation of our HTML DOM tree:</para> - <programlisting language="xml">... </tr> - <tr> - <td>Swinging headset</td> - <td>3218</td> - </tr> - <tr> - <td>200W Stereo Amplifier</td> - <td>9921</td> - </tr> - </tbody> ...</programlisting> + <programlisting language="xml">... + </tr> + <tr> + <td>Swinging headset</td> + <td>3218</td> + </tr> + <tr> + <td>200W Stereo Amplifier</td> + <td>9921</td> + </tr> +</tbody> ...</programlisting> </callout> </calloutlist> @@ -1084,7 +1255,9 @@ public class Article2Html { builder.setErrorHandler(new MySaxErrorHandler(System.out)); - htmlResult = new HtmlTree("Available articles", new String[] { <co linkends="programlisting_catalog2html_glue_createhtmldom_co" xml:id="programlisting_catalog2html_glue_createhtmldom" /> + htmlResult = new HtmlTree("Available articles", new String[] { <co + linkends="programlisting_catalog2html_glue_createhtmldom_co" + xml:id="programlisting_catalog2html_glue_createhtmldom"/> "Article Description", "Order Number" }); } @@ -1104,32 +1277,43 @@ public class Article2Html { // builder.build(filename).getRootElement().getChildren(); builder.build(getClass().getClassLoader().getResource(filename)).getRootElement().getChildren(); - for (final Element item : items) { <co linkends="programlisting_catalog2html_glue_prodloop_co" xml:id="programlisting_catalog2html_glue_prodloop" /> + for (final Element item : items) { <co + linkends="programlisting_catalog2html_glue_prodloop_co" + xml:id="programlisting_catalog2html_glue_prodloop"/> htmlResult.appendItem(item.getText(), - item.getAttributeValue("orderNo")); <co linkends="programlisting_catalog2html_glue_insertprod_co" xml:id="programlisting_catalog2html_glue_insertprod" /> + item.getAttributeValue("orderNo")); <co + linkends="programlisting_catalog2html_glue_insertprod_co" + xml:id="programlisting_catalog2html_glue_insertprod"/> } - htmlResult.serialize(out); <co linkends="programlisting_catalog2html_glue_serialize_co" xml:id="programlisting_catalog2html_glue_serialize" /> + htmlResult.serialize(out); <co + linkends="programlisting_catalog2html_glue_serialize_co" + xml:id="programlisting_catalog2html_glue_serialize"/> } }</programlisting> <calloutlist> - <callout arearefs="programlisting_catalog2html_glue_createhtmldom" xml:id="programlisting_catalog2html_glue_createhtmldom_co"> - <para>Create an instance holding a HTML <xref linkend="glo_DOM" /> with a table header containing the + <callout arearefs="programlisting_catalog2html_glue_createhtmldom" + xml:id="programlisting_catalog2html_glue_createhtmldom_co"> + <para>Create an instance holding a HTML <xref + linkend="glo_DOM"/> with a table header containing the strings <emphasis>Article Description</emphasis> and <emphasis>Order Number</emphasis>.</para> </callout> - <callout arearefs="programlisting_catalog2html_glue_prodloop" xml:id="programlisting_catalog2html_glue_prodloop_co"> + <callout arearefs="programlisting_catalog2html_glue_prodloop" + xml:id="programlisting_catalog2html_glue_prodloop_co"> <para>Iterate over all product nodes.</para> </callout> - <callout arearefs="programlisting_catalog2html_glue_insertprod" xml:id="programlisting_catalog2html_glue_insertprod_co"> + <callout arearefs="programlisting_catalog2html_glue_insertprod" + xml:id="programlisting_catalog2html_glue_insertprod_co"> <para>Insert the product's name an order number into the - HTML <xref linkend="glo_DOM" />.</para> + HTML <xref linkend="glo_DOM"/>.</para> </callout> - <callout arearefs="programlisting_catalog2html_glue_serialize" xml:id="programlisting_catalog2html_glue_serialize_co"> - <para>Serialize the completed HTML <xref linkend="glo_DOM" /> + <callout arearefs="programlisting_catalog2html_glue_serialize" + xml:id="programlisting_catalog2html_glue_serialize_co"> + <para>Serialize the completed HTML <xref linkend="glo_DOM"/> tree to the output stream.</para> </callout> </calloutlist> @@ -1140,13 +1324,13 @@ public class Article2Html { </section> <section xml:id="sda1SectCleanHtml"> - <title>Cleaning up <xref linkend="glo_HTML" />.</title> + <title>Cleaning up <xref linkend="glo_HTML"/>.</title> <qandaset defaultlabel="qanda" xml:id="sda1QandaCleanHtml"> <qandadiv> <qandaentry> <question> - <para>Consider the following <xref linkend="glo_HTML" /> legacy + <para>Consider the following <xref linkend="glo_HTML"/> legacy document:</para> <programlisting language="xml"><html xmlns='http://www.w3.org/1999/xhtml'> @@ -1162,9 +1346,10 @@ public class Article2Html { </html></programlisting> <para>The pre-HTML5 <code>align='...'</code>attribute is - deprecated and has been replaced by <xref linkend="glo_CSS" /> + deprecated and has been replaced by <xref linkend="glo_CSS"/> <code>style="vertical-align: ...;" or </code><code>style="float: - ...;"</code> <link xlink:href="http://www.w3schools.com/tags/att_img_align.asp">respectively</link>:</para> + ...;"</code> <link + xlink:href="http://www.w3schools.com/tags/att_img_align.asp">respectively</link>:</para> <programlisting language="xml"><html xmlns="http://www.w3.org/1999/xhtml"> <head> @@ -1179,7 +1364,7 @@ public class Article2Html { </html></programlisting> <para>Write a JDom based filter application which transforms - these legacy declarations to <xref linkend="glo_CSS" /> + these legacy declarations to <xref linkend="glo_CSS"/> accordingly.</para> <tip> @@ -1188,37 +1373,45 @@ public class Article2Html { <orderedlist> <listitem> <para>Start by an identity transformation: Parse your - <xref linkend="glo_HTML" /> document to a <xref linkend="glo_DOM" /> tree and simply serialize this tree to + <xref linkend="glo_HTML"/> document to a <xref + linkend="glo_DOM"/> tree and simply serialize this tree to standard output.</para> </listitem> <listitem> - <para>Modify the intermediate <xref linkend="glo_DOM" /> - tree. The recursive descent method from <xref linkend="sda1SectElementVisualize" /> allows for retrieving + <para>Modify the intermediate <xref linkend="glo_DOM"/> + tree. The recursive descent method from <xref + linkend="sda1SectElementVisualize"/> allows for retrieving all <tag class="emptytag">img ...</tag> elements.</para> </listitem> <listitem> - <para>The <methodname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#getAttribute(java.lang.String)">getAttribute(...)</methodname> - method allows for identifying relevant <tag class="emptytag">img align='...'</tag> elements.</para> + <para>The <methodname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#getAttribute(java.lang.String)">getAttribute(...)</methodname> + method allows for identifying relevant <tag + class="emptytag">img align='...'</tag> elements.</para> </listitem> <listitem> <para>You may then modify <tag class="emptytag">img - align='...'</tag> elements using <methodname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#removeAttribute(org.jdom2.Attribute)">removeAttribute(...)</methodname> - and <methodname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#setAttribute(org.jdom2.Attribute)">setAttribute(...)</methodname>.</para> + align='...'</tag> elements using <methodname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#removeAttribute(org.jdom2.Attribute)">removeAttribute(...)</methodname> + and <methodname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#setAttribute(org.jdom2.Attribute)">setAttribute(...)</methodname>.</para> </listitem> </orderedlist> </tip> - <para>Optional: Supply an XSLT doing the same job as your <xref linkend="glo_Java" /> application and compare both solution - variants. You may want to read <quote xlink:href="http://www.usingxml.com/Transforms/XslIdentity#TheIdentityTransform">The + <para>Optional: Supply an XSLT doing the same job as your <xref + linkend="glo_Java"/> application and compare both solution + variants. You may want to read <quote + xlink:href="http://www.usingxml.com/Transforms/XslIdentity#TheIdentityTransform">The Identity Transform</quote>. This enables you to:</para> <orderedlist> <listitem> - <para>Copy most <xref linkend="glo_HTML" /> from input to - output like in your <xref linkend="glo_Java" /> + <para>Copy most <xref linkend="glo_HTML"/> from input to + output like in your <xref linkend="glo_Java"/> solution.</para> </listitem> @@ -1239,7 +1432,8 @@ public class Article2Html { <code>html2html.xsl</code> style sheet.</para> <caution> - <para>Both solution variants do not account for elements <tag class="emptytag">img ... align='...' style='...'</tag> already + <para>Both solution variants do not account for elements <tag + class="emptytag">img ... align='...' style='...'</tag> already defining a <code language="xml">style</code> attribute. Any such existing value will be overridden. It is however straightforward extending the current solution to append to @@ -1254,10 +1448,10 @@ public class Article2Html { </section> <section xml:id="domJavaScript"> - <title>Using <xref linkend="glo_DOM" /> with HTML/Javascript</title> + <title>Using <xref linkend="glo_DOM"/> with HTML/Javascript</title> <figure xml:id="sda1_dom_fig_domJavascript"> - <title><xref linkend="glo_DOM" /> and + <title><xref linkend="glo_DOM"/> and <productname>Javascript</productname></title> <itemizedlist> @@ -1267,13 +1461,13 @@ public class Article2Html { </listitem> <listitem> - <para>Full <xref linkend="glo_DOM" /> support.</para> + <para>Full <xref linkend="glo_DOM"/> support.</para> </listitem> </itemizedlist> </figure> <figure xml:id="sda1_dom_fig_domJavascriptExample"> - <title><xref linkend="glo_DOM" /> <productname>Javascript</productname> + <title><xref linkend="glo_DOM"/> <productname>Javascript</productname> example</title> <programlisting language="javascript">function sortables_init() { @@ -1289,12 +1483,13 @@ public class Article2Html { </figure> <figure xml:id="sda1_dom_fig_domJavascriptDemo"> - <title><xref linkend="glo_DOM" /> <productname>Javascript</productname> + <title><xref linkend="glo_DOM"/> <productname>Javascript</productname> demo</title> <itemizedlist> <listitem> - <para><uri xlink:href="https://kryogenix.org/code/browser/sorttable">https://kryogenix.org/code/browser/sorttable</uri> + <para><uri + xlink:href="https://kryogenix.org/code/browser/sorttable">https://kryogenix.org/code/browser/sorttable</uri> or <link xlink:href="/Sda1/Ref/src/tablesort.html">local copy</link></para> </listitem> @@ -1325,14 +1520,15 @@ public class Article2Html { </section> <section xml:id="domXpath"> - <title><xref linkend="glo_DOM" /> and <acronym xlink:href="https://www.w3.org/TR/xpath">XPath</acronym></title> + <title><xref linkend="glo_DOM"/> and <acronym + xlink:href="https://www.w3.org/TR/xpath">XPath</acronym></title> <figure xml:id="sda1_dom_fig_whyXpath"> - <title>Why using <xref linkend="glo_XPath" /> ?</title> + <title>Why using <xref linkend="glo_XPath"/> ?</title> <itemizedlist> <listitem> - <para><xref linkend="sda1_dom_fig_TreeTraversal" /> + <para><xref linkend="sda1_dom_fig_TreeTraversal"/> cumbersome/error-prone on complex hierarchies.</para> </listitem> @@ -1347,43 +1543,50 @@ public class Article2Html { </figure> <figure xml:id="sda1_dom_fig_xpathJava"> - <title><xref linkend="glo_XPath" /> and <xref linkend="glo_Jdom" /></title> + <title><xref linkend="glo_XPath"/> and <xref + linkend="glo_Jdom"/></title> <itemizedlist> <listitem> - <para>Addressing node sets in <xref linkend="glo_XML" /> + <para>Addressing node sets in <xref linkend="glo_XML"/> trees.</para> </listitem> <listitem> - <para>Conceptional <xref linkend="glo_SQL" /> similarity.</para> + <para>Conceptional <xref linkend="glo_SQL"/> similarity.</para> </listitem> <listitem> - <para><link xlink:href="https://docs.oracle.com/javase/tutorial/collections">Collections</link> + <para><link + xlink:href="https://docs.oracle.com/javase/tutorial/collections">Collections</link> representing result sets.</para> </listitem> </itemizedlist> </figure> <figure xml:id="sda1_fig_jdomMavenConfigXpath"> - <title><xref linkend="glo_XPath" /> on top of <xref linkend="glo_Jdom" /></title> + <title><xref linkend="glo_XPath"/> on top of <xref + linkend="glo_Jdom"/></title> - <programlisting language="xml"><dependency> <emphasis role="bold"><!-- Jdom itself --></emphasis> + <programlisting language="xml"><dependency> <emphasis + role="bold"><!-- Jdom itself --></emphasis> <groupId>org.jdom</groupId> - <artifactId><link xlink:href="https://mvnrepository.com/artifact/org.jdom/jdom2">jdom2</link></artifactId> + <artifactId><link + xlink:href="https://mvnrepository.com/artifact/org.jdom/jdom2">jdom2</link></artifactId> <version>2.0.6</version> </dependency> <dependency> <emphasis role="bold"><!-- XPath support for Jdom --></emphasis> <groupId>jaxen</groupId> - <artifactId><link xlink:href="https://mvnrepository.com/artifact/jaxen/jaxen">jaxen</link></artifactId> + <artifactId><link + xlink:href="https://mvnrepository.com/artifact/jaxen/jaxen">jaxen</link></artifactId> <version>1.1.6</version> </dependency> ...</programlisting> </figure> <figure xml:id="sda1_dom_fig_htmlImg"> - <title><xref linkend="glo_HTML" /> containing <tag class="starttag">img</tag> tags.</title> + <title><xref linkend="glo_HTML"/> containing <tag + class="starttag">img</tag> tags.</title> <programlisting language="xml"><html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Picture gallery</title></head> @@ -1415,7 +1618,8 @@ public class Article2Html { <listitem> <para>Possibly additional search restrictions <abbrev>e.g.:</abbrev> <quote>searching for <tag class="emptytag">img</tag> elements - missing an <varname xlink:href="https://www.w3schools.com/tags/att_img_alt.asp">alt</varname> + missing an <varname + xlink:href="https://www.w3schools.com/tags/att_img_alt.asp">alt</varname> attribute</quote>.</para> </listitem> </itemizedlist> @@ -1426,9 +1630,9 @@ public class Article2Html { script extracting images.</title> <informaltable border="1"> - <colgroup width="64%" /> + <colgroup width="64%"/> - <colgroup width="36%" /> + <colgroup width="36%"/> <tr> <td valign="top"><programlisting language="xml"><xsl:stylesheet version="1.0" @@ -1445,13 +1649,15 @@ public class Article2Html { </xsl:stylesheet></programlisting></td> - <td valign="top"><para>Result acting on <xref linkend="sda1_dom_fig_htmlImg" />:</para><screen>inline.gif one.gif two.gif</screen></td> + <td valign="top"><para>Result acting on <xref + linkend="sda1_dom_fig_htmlImg"/>:</para><screen>inline.gif one.gif two.gif</screen></td> </tr> </informaltable> </figure> <para>Note the necessity for <code>html</code> namespace (by prefix) - inclusion into the <acronym xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> expression in + inclusion into the <acronym + xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> expression in <code><xsl:for-each select="//html:img"></code>. A simple <code>select="//img"></code> results in an empty node set. Executing the <abbrev xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> script @@ -1459,19 +1665,25 @@ public class Article2Html { <code>inline.gif one.gif two.gif</code>.</para> <para>As a preparation for an application checking image accessibility we - want to rewrite the above <xref linkend="glo_XSL" /> as a <xref linkend="glo_Java" /> application. A simple approach may pipe the <abbrev xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> output to our + want to rewrite the above <xref linkend="glo_XSL"/> as a <xref + linkend="glo_Java"/> application. A simple approach may pipe the <abbrev + xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> output to our application which then executes the readability checks. Instead we - implement an <acronym xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> based search - within our <xref linkend="glo_Java" /> application. Trying to resemble the + implement an <acronym + xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> based search + within our <xref linkend="glo_Java"/> application. Trying to resemble the <abbrev xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> actions as - closely as possible our application will search for <link xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Element.html">Element</link> - nodes using the <acronym xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> expression + closely as possible our application will search for <link + xlink:href="https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Element.html">Element</link> + nodes using the <acronym + xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> expression <code>//html:img</code>.</para> <figure xml:id="sda1_dom_fig_domSaxImgParse"> <title>Setting up the parser</title> - <programlisting language="java">public class <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/NoCast/src/main/java/de/hdm_stuttgart/mi/sda1/nocast/DomXpath.java">DomXpath</link> { + <programlisting language="java">public class <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/NoCast/src/main/java/de/hdm_stuttgart/mi/sda1/nocast/DomXpath.java">DomXpath</link> { private final SAXBuilder builder = new SAXBuilder(); public List<Element> process(final String xhtmlFilename) @@ -1483,50 +1695,67 @@ public class Article2Html { }</programlisting> <tip> - <para>Complete code <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/NoCast">available + <para>Complete code <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/tree/master/P/Sda1/NoCast">available here</link>.</para> </tip> </figure> <figure xml:id="sda1_dom_fig_domXpathImgSearch"> - <title>Search using <xref linkend="glo_XPath" /> + <title>Search using <xref linkend="glo_XPath"/> <code>//html:img</code></title> - <programlisting language="java">static final Namespace htmlNamespace <co linkends="sda1_dom_fig_domXpathImgSearch-1" xml:id="sda1_dom_fig_domXpathImgSearch-1-co" /> = + <programlisting language="java">static final Namespace htmlNamespace <co + linkends="sda1_dom_fig_domXpathImgSearch-1" + xml:id="sda1_dom_fig_domXpathImgSearch-1-co"/> = Namespace.getNamespace("html", "http://www.w3.org/1999/xhtml"); static final XPathExpression<Element> xpathSearchImg = XPathFactory.instance().compile( - "//html:img" <co linkends="sda1_dom_fig_domXpathImgSearch-2" xml:id="sda1_dom_fig_domXpathImgSearch-2-co" />, - new ElementFilter()<co linkends="sda1_dom_fig_domXpathImgSearch-3" xml:id="sda1_dom_fig_domXpathImgSearch-3-co" />, - null <co linkends="sda1_dom_fig_domXpathImgSearch-4" xml:id="sda1_dom_fig_domXpathImgSearch-4-co" />, - htmlNamespace <co linkends="sda1_dom_fig_domXpathImgSearch-5" xml:id="sda1_dom_fig_domXpathImgSearch-5-co" />);</programlisting> + "//html:img" <co linkends="sda1_dom_fig_domXpathImgSearch-2" + xml:id="sda1_dom_fig_domXpathImgSearch-2-co"/>, + new ElementFilter()<co linkends="sda1_dom_fig_domXpathImgSearch-3" + xml:id="sda1_dom_fig_domXpathImgSearch-3-co"/>, + null <co linkends="sda1_dom_fig_domXpathImgSearch-4" + xml:id="sda1_dom_fig_domXpathImgSearch-4-co"/>, + htmlNamespace <co linkends="sda1_dom_fig_domXpathImgSearch-5" + xml:id="sda1_dom_fig_domXpathImgSearch-5-co"/>);</programlisting> </figure> <calloutlist> - <callout arearefs="sda1_dom_fig_domXpathImgSearch-1-co" xml:id="sda1_dom_fig_domXpathImgSearch-1"> - <para>Associating prefix <code>html</code> and <xref linkend="glo_HTML" /> namespace + <callout arearefs="sda1_dom_fig_domXpathImgSearch-1-co" + xml:id="sda1_dom_fig_domXpathImgSearch-1"> + <para>Associating prefix <code>html</code> and <xref + linkend="glo_HTML"/> namespace <code>http://www.w3.org/1999/xhtml</code>.</para> </callout> - <callout arearefs="sda1_dom_fig_domXpathImgSearch-2-co" xml:id="sda1_dom_fig_domXpathImgSearch-2"> + <callout arearefs="sda1_dom_fig_domXpathImgSearch-2-co" + xml:id="sda1_dom_fig_domXpathImgSearch-2"> <para>Searching <tag class="starttag">img</tag> elements belonging to the namespace <code>http://www.w3.org/1999/xhtml</code> linked by the <code>html</code> prefix.</para> </callout> - <callout arearefs="sda1_dom_fig_domXpathImgSearch-3-co" xml:id="sda1_dom_fig_domXpathImgSearch-3"> - <para>Selecting only <classname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html">Element</classname> - instances rather than other sub classed objects below <link xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Content.html">Content</link>.</para> + <callout arearefs="sda1_dom_fig_domXpathImgSearch-3-co" + xml:id="sda1_dom_fig_domXpathImgSearch-3"> + <para>Selecting only <classname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html">Element</classname> + instances rather than other sub classed objects below <link + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/Content.html">Content</link>.</para> </callout> - <callout arearefs="sda1_dom_fig_domXpathImgSearch-4-co" xml:id="sda1_dom_fig_domXpathImgSearch-4"> - <para>Using no parameters. See <link xlink:href="http://www.jdom.org/pipermail/jdom-interest/2012-May/016850.html">[jdom-interest] + <callout arearefs="sda1_dom_fig_domXpathImgSearch-4-co" + xml:id="sda1_dom_fig_domXpathImgSearch-4"> + <para>Using no parameters. See <link + xlink:href="http://www.jdom.org/pipermail/jdom-interest/2012-May/016850.html">[jdom-interest] XPath examples</link> for parameterized queries.</para> </callout> - <callout arearefs="sda1_dom_fig_domXpathImgSearch-5-co" xml:id="sda1_dom_fig_domXpathImgSearch-5"> - <para>Using previously defined namespace. The ellipsis in <methodname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/xpath/XPathFactory.html#compile(java.lang.String,%20org.jdom2.filter.Filter,%20java.util.Map,%20org.jdom2.Namespace...)">compile</methodname> + <callout arearefs="sda1_dom_fig_domXpathImgSearch-5-co" + xml:id="sda1_dom_fig_domXpathImgSearch-5"> + <para>Using previously defined namespace. The ellipsis in <methodname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/xpath/XPathFactory.html#compile(java.lang.String,%20org.jdom2.filter.Filter,%20java.util.Map,%20org.jdom2.Namespace...)">compile</methodname> supports multiple namespace definitions.</para> </callout> </calloutlist> @@ -1554,7 +1783,8 @@ static final XPathExpression<Element> xpathSearchImg = <qandadiv> <qandaentry> <question> - <para>We want to extend the example given in <xref linkend="domFindImages" /> by testing the existence and checking + <para>We want to extend the example given in <xref + linkend="domFindImages"/> by testing the existence and checking for readability of referenced images. The following HTML document contains <quote>dead</quote> image references:</para> @@ -1586,15 +1816,18 @@ static final XPathExpression<Element> xpathSearchImg = </body> </html></programlisting> - <para>Write an application which checks for readability of <abbrev xlink:href="https://www.ietf.org/rfc/rfc1738.txt">URL</abbrev> + <para>Write an application which checks for readability of <abbrev + xlink:href="https://www.ietf.org/rfc/rfc1738.txt">URL</abbrev> image references to <emphasis>external</emphasis> Servers starting either with <code>http://</code> or <code>https://</code> ignoring other protocol types. Internal image references referring to the <quote>current</quote> server typically look like <code><img src="/images/test.gif"</code>. So in order to distinguish these - two types of references we may use the XSL built in function <link xlink:href="http://www.cafeconleche.org/books/bible2/chapters/ch17.html">starts-with()</link> + two types of references we may use the XSL built in function <link + xlink:href="http://www.cafeconleche.org/books/bible2/chapters/ch17.html">starts-with()</link> testing for the <code>http</code> or <code>https</code> protocol - definition part of an <abbrev xlink:href="https://www.ietf.org/rfc/rfc1738.txt">URL</abbrev>. + definition part of an <abbrev + xlink:href="https://www.ietf.org/rfc/rfc1738.txt">URL</abbrev>. <code>ftp</code> addresses shall be ignored completely. A possible output corresponding to the above example reads:</para> @@ -1612,7 +1845,8 @@ http://www.hdm-stuttgart.de/rotfl.gif, HTTP Status: false</screen> <para>Moreover a web server may return misleading response codes if deciding your user agent is unable to handle the current resource's content type in question. You may catch a glimpse of - related problems by reading <link xlink:href="https://stackoverflow.com/questions/1378199/how-to-check-if-a-url-exists-or-returns-404-with-java">How + related problems by reading <link + xlink:href="https://stackoverflow.com/questions/1378199/how-to-check-if-a-url-exists-or-returns-404-with-java">How to check if a URL exists or returns 404 with Java?</link>.</para> @@ -1631,18 +1865,22 @@ http://www.hdm-stuttgart.de/rotfl.gif, HTTP Status: false</screen> <itemizedlist> <listitem> - <para><link xlink:href="http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-namespaces.jsp">Java + <para><link + xlink:href="http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-namespaces.jsp">Java XML - JDOM2 - Namespaces</link></para> </listitem> <listitem> - <para><link xlink:href="http://www.jdom.org/pipermail/jdom-interest/2012-May/016850.html">XPath + <para><link + xlink:href="http://www.jdom.org/pipermail/jdom-interest/2012-May/016850.html">XPath examples</link></para> </listitem> <listitem> - <para>For analyzing the accessibility of referenced <xref linkend="glo_HTTP" /> / <acronym>HTTPS</acronym> resources - see the previously mentioned discussion in <link xlink:href="https://stackoverflow.com/questions/1378199/how-to-check-if-a-url-exists-or-returns-404-with-java">How + <para>For analyzing the accessibility of referenced <xref + linkend="glo_HTTP"/> / <acronym>HTTPS</acronym> resources + see the previously mentioned discussion in <link + xlink:href="https://stackoverflow.com/questions/1378199/how-to-check-if-a-url-exists-or-returns-404-with-java">How to check if a URL exists or returns 404 with Java?</link>.</para> </listitem> @@ -1652,7 +1890,8 @@ http://www.hdm-stuttgart.de/rotfl.gif, HTTP Status: false</screen> <answer> <para>We are interested in the set of images within a given HTML - document containing an <link xlink:href="https://www.w3.org/Addressing">URL</link> reference + document containing an <link + xlink:href="https://www.w3.org/Addressing">URL</link> reference starting with either of:</para> <itemizedlist> @@ -1669,7 +1908,8 @@ http://www.hdm-stuttgart.de/rotfl.gif, HTTP Status: false</screen> </listitem> </itemizedlist> - <para>This may be achieved by the following <acronym xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> + <para>This may be achieved by the following <acronym + xlink:href="https://www.w3.org/TR/xpath">XPath</acronym> expression:</para> <programlisting language="xpath">//html:img[starts-with(@src, 'http://') or @@ -1701,23 +1941,26 @@ break;</programlisting> <figure xml:id="sda1_dom_fig_domXpathVariables"> <title>Parameterized search expressions</title> - <programlisting language="none">Map<String, Object> <link xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/VerifyInternalReferences/src/main/java/dom/xpath/CheckLocalReferences.java">xpathVarsNamespacePrefix</link> = new HashMap<>(); + <programlisting language="none">Map<String, Object> <link + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/VerifyInternalReferences/src/main/java/dom/xpath/CheckLocalReferences.java">xpathVarsNamespacePrefix</link> = new HashMap<>(); xpathVarsNamespacePrefix.put("cssClass", null) ; ... XPathExpression<Element> searchCssClass = XPathFactory.instance().compile( "//html:*[@class = <emphasis role="red">$cssClass</emphasis>]", new ElementFilter(), xpathVarsNamespacePrefix, htmlNamespace); -searchCssClass.setVariable(<emphasis>"<emphasis role="red">cssClass</emphasis>"</emphasis>, "<emphasis role="red">header</emphasis>"); +searchCssClass.setVariable(<emphasis>"<emphasis role="red">cssClass</emphasis>"</emphasis>, "<emphasis + role="red">header</emphasis>"); searchCssClass.evaluate(htmlInput) ... // Reuse by changing $cssClass -searchCssClass.setVariable("<emphasis role="red">cssClass</emphasis>", "<emphasis role="red">footer</emphasis>"); +searchCssClass.setVariable("<emphasis role="red">cssClass</emphasis>", "<emphasis + role="red">footer</emphasis>"); searchCssClass.evaluate(htmlInput) ...</programlisting> </figure> <qandaset defaultlabel="qanda" xml:id="sda1QandaVerifyInternalReferences"> - <title><xref linkend="glo_HTML" /> internal reference + <title><xref linkend="glo_HTML"/> internal reference verification</title> <qandadiv> @@ -1731,7 +1974,8 @@ searchCssClass.evaluate(htmlInput) ...</programlisting> </head> <body><h1 <emphasis role="red">id="start"</emphasis>>Introduction</h1><p>We categorize for <a - <emphasis role="red">href="#nativeExec"</emphasis>>native</a> and <a <emphasis role="red">href="#vmBased"</emphasis>>VM based</a> <a + <emphasis role="red">href="#nativeExec"</emphasis>>native</a> and <a <emphasis + role="red">href="#vmBased"</emphasis>>VM based</a> <a href="https://en.wikipedia.org/wiki/Runtime_system">runtimes</a>.</p><h1 <emphasis role="red">id="languages"</emphasis>>Languages</h1><dl> <dt <emphasis role="red">id="nativeExec"</emphasis>>Native execution code</dt> @@ -1790,9 +2034,12 @@ Error: matching target id 'newSection' not found</screen> </listitem> </orderedlist> - <para>Both parts may be implemented using <xref linkend="glo_XPath" /> expressions. For the second task you are - asked to reuse your <classname xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/xpath/XPathExpression.html">XPathExpression</classname> - using the technique being described in <xref linkend="sda1_dom_fig_domXpathVariables" />.</para> + <para>Both parts may be implemented using <xref + linkend="glo_XPath"/> expressions. For the second task you are + asked to reuse your <classname + xlink:href="http://www.jdom.org/docs/apidocs/org/jdom2/xpath/XPathExpression.html">XPathExpression</classname> + using the technique being described in <xref + linkend="sda1_dom_fig_domXpathVariables"/>.</para> </question> <answer> @@ -1800,19 +2047,22 @@ Error: matching target id 'newSection' not found</screen> <para role="eclipse">Sda1/VerifyInternalReferences</para> </annotation> - <para><code>h</code> denoting the <xref linkend="glo_HTML" /> + <para><code>h</code> denoting the <xref linkend="glo_HTML"/> namespace prefix we search for local references using:</para> <programlisting language="xpath">//h:*[starts-with(@href, '#')]</programlisting> - <para>This task is quite similar to <xref linkend="sda1QandaVerifyImgReadable" />. We create a reusable <xref linkend="glo_XPath" /> expression searching for targets:</para> + <para>This task is quite similar to <xref + linkend="sda1QandaVerifyImgReadable"/>. We create a reusable <xref + linkend="glo_XPath"/> expression searching for targets:</para> <programlisting language="xpath">//h:*[starts-with(@id, $" + ID_VAR_KEY + ")]</programlisting> <para>Resolving the variable <varname>ID_VAR_KEY</varname> this actually contains <code>//h:*[starts-with(@id, $targetId)]</code>. This latter query parameter <varname>$targetId</varname> will be - set each time prior to executing the path expression in <classname xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/VerifyInternalReferences/src/main/java/dom/xpath/CheckLocalReferences.java">CheckLocalReferences</classname>:</para> + set each time prior to executing the path expression in <classname + xlink:href="https://gitlab.mi.hdm-stuttgart.de/goik/GoikLectures/blob/master/P/Sda1/VerifyInternalReferences/src/main/java/dom/xpath/CheckLocalReferences.java">CheckLocalReferences</classname>:</para> <programlisting language="java">searchTargetId.setVariable(ID_VAR_KEY, id); final int targetCount = searchTargetId.evaluate(htmlInput).size();</programlisting> @@ -1823,16 +2073,19 @@ final int targetCount = searchTargetId.evaluate(htmlInput).size();</programlisti </section> <section xml:id="domXsl"> - <title><xref linkend="glo_DOM" /> and <abbrev xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev></title> - - <para><xref linkend="glo_Java" /> based <xref linkend="glo_XML" /> - applications may use XSL style sheets for processing. A <xref linkend="glo_DOM" /> tree may for example be transformed into another tree. - The package <link xlink:href="https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/package-frame.html">javax.xml.transform</link> + <title><xref linkend="glo_DOM"/> and <abbrev + xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev></title> + + <para><xref linkend="glo_Java"/> based <xref linkend="glo_XML"/> + applications may use XSL style sheets for processing. A <xref + linkend="glo_DOM"/> tree may for example be transformed into another tree. + The package <link + xlink:href="https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/package-frame.html">javax.xml.transform</link> provides interfaces and classes for this purpose. We consider the following product catalog example:</para> <figure xml:id="climbingCatalog"> - <title>A simplified <xref linkend="glo_XML" /> product catalog</title> + <title>A simplified <xref linkend="glo_XML"/> product catalog</title> <programlisting language="xml"><catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="catalog.xsd"> @@ -1945,8 +2198,11 @@ final int targetCount = searchTargetId.evaluate(htmlInput).size();</programlisti </xsl:stylesheet></programlisting> </figure> - <para>As a preparation for <xref linkend="sda1SectCatalog2html" /> we now - demonstrate the usage of <abbrev xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> within a <xref linkend="glo_Java" /> application. This is done by a <link xlink:href="https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/Transformer.html">Transformer</link> + <para>As a preparation for <xref linkend="sda1SectCatalog2html"/> we now + demonstrate the usage of <abbrev + xlink:href="https://www.w3.org/Style/XSL">XSL</abbrev> within a <xref + linkend="glo_Java"/> application. This is done by a <link + xlink:href="https://docs.oracle.com/javase/10/docs/api/javax/xml/transform/Transformer.html">Transformer</link> instance:</para> <figure xml:id="xml2xml"> @@ -2013,11 +2269,12 @@ public class Xml2HtmlDriver { <section xml:id="sda1SectNamespaceElementStatistics"> <title>Namespace / elements statistics</title> - <qandaset defaultlabel="qanda" xml:id="sda1QandaNamespaceElementStatistics"> + <qandaset defaultlabel="qanda" + xml:id="sda1QandaNamespaceElementStatistics"> <qandadiv> <qandaentry> <question> - <para>Consider the following <xref linkend="glo_XML" /> document + <para>Consider the following <xref linkend="glo_XML"/> document example:</para> <programlisting language="xml"><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" @@ -2055,9 +2312,9 @@ public class Xml2HtmlDriver { </xsl:stylesheet></programlisting> <informaltable border="1"> - <colgroup width="31%" /> + <colgroup width="31%"/> - <colgroup width="69%" /> + <colgroup width="69%"/> <tr> <td valign="top"><para>The above sample document does @@ -2087,18 +2344,20 @@ public class Xml2HtmlDriver { <para>Having no namespace prefix.</para> </glossdef> </glossentry> - </glosslist><para>Write a <xref linkend="glo_Jdom" /> + </glosslist><para>Write a <xref linkend="glo_Jdom"/> application which generates statistical data like being - represented by <xref linkend="glo_HTML" /> to the + represented by <xref linkend="glo_HTML"/> to the right.</para><para>Your application is expected to operate - on <emphasis role="bold">arbitrary</emphasis> <xref linkend="glo_XML" /> input documents.</para><para>Providing - suitable unit tests is an <emphasis role="bold">inherent</emphasis> part of this + on <emphasis role="bold">arbitrary</emphasis> <xref + linkend="glo_XML"/> input documents.</para><para>Providing + suitable unit tests is an <emphasis + role="bold">inherent</emphasis> part of this exercise!</para></td> <td><informalfigure> <mediaobject> <imageobject> - <imagedata fileref="Ref/Fig/nspaceElemFrequency.png" /> + <imagedata fileref="Ref/Fig/nspaceElemFrequency.png"/> </imageobject> </mediaobject> </informalfigure></td> @@ -2110,7 +2369,8 @@ public class Xml2HtmlDriver { the XPath expression <code>//*</code>. Then construct a <classname>Map<String, Set<...>></classname> having namespaces as keys and sets of element names among with - frequencies as values. Mind an appropriate <methodname xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals()</methodname> + frequencies as values. Mind an appropriate <methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals()</methodname> definition!</para> </tip> </question> diff --git a/ws/Docbook/CustomLayer/webhelp/common/images/yoga-exercise.svg b/ws/Docbook/CustomLayer/webhelp/common/images/yoga-exercise.svg new file mode 100644 index 000000000..518c59f59 --- /dev/null +++ b/ws/Docbook/CustomLayer/webhelp/common/images/yoga-exercise.svg @@ -0,0 +1,297 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="35.658375mm" + height="31.312292mm" + viewBox="0 0 35.658375 31.312292" + version="1.1" + id="svg8" + inkscape:version="0.92.3 (2405546, 2018-03-11)" + sodipodi:docname="yoga-exercise.svg"> + <defs + id="defs2"> + <linearGradient + x1="204.74001" + x2="202.25999" + gradientTransform="scale(1.0599,0.94347)" + y1="224.53" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="280.39999" + id="linearGradient2389" /> + <linearGradient + x1="86.697998" + x2="80.221001" + gradientTransform="scale(1.0554,0.9475)" + y1="-98.280998" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="-45.063" + id="linearGradient2441" /> + <linearGradient + x1="590.33002" + y1="36.240002" + gradientTransform="scale(0.77267,1.2942)" + x2="587.31" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="89.857002" + id="linearGradient3022" /> + <linearGradient + id="linearGradient1515"> + <stop + offset="0" + style="stop-color:#ffffff" + id="stop1516" /> + <stop + offset="1" + style="stop-color:#ffffff;stop-opacity:0" + id="stop1517" /> + </linearGradient> + <linearGradient + x1="538.10999" + x2="534.98999" + gradientTransform="scale(0.91191,1.0966)" + y1="61.734001" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="88.251999" + id="linearGradient1657" /> + <linearGradient + x1="65.357002" + x2="52.743" + gradientTransform="scale(1.4482,0.69053)" + y1="66.162003" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="99.991997" + id="linearGradient2391" /> + <linearGradient + x1="72.939003" + x2="59.365002" + gradientTransform="scale(1.3374,0.74774)" + y1="72.555" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="115.15" + id="linearGradient3129" /> + <linearGradient + x1="154.21001" + y1="104.77" + gradientTransform="scale(0.96545,1.0358)" + x2="87.621002" + gradientUnits="userSpaceOnUse" + y2="138.91" + id="linearGradient1512"> + <stop + offset="0" + style="stop-color:#000000;stop-opacity:.70056" + id="stop1519" /> + <stop + offset="1" + style="stop-color:#000000;stop-opacity:0" + id="stop1520" /> + </linearGradient> + <linearGradient + x1="137.73" + x2="123.21" + gradientTransform="scale(0.74082,1.3498)" + y1="66.420998" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="73.769997" + id="linearGradient1638" /> + <radialGradient + r="51.667" + cx="24.825001" + cy="176.56" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1806" + fy="141.28999" + fx="30.802" + id="radialGradient1528" /> + <linearGradient + x1="101.22" + x2="69.200996" + gradientTransform="scale(1.3179,0.75881)" + y1="289.5" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1515" + y2="387.14001" + id="linearGradient2403" /> + <linearGradient + id="linearGradient1806"> + <stop + offset="0" + style="stop-color:#000000;stop-opacity:.40784" + id="stop1807" /> + <stop + offset=".64778" + style="stop-color:#000000;stop-opacity:.079096" + id="stop3276" /> + <stop + offset="1" + style="stop-color:#000000;stop-opacity:0" + id="stop1808" /> + </linearGradient> + <linearGradient + x1="78.879997" + x2="75.334" + gradientTransform="scale(1.1304,0.88467)" + y1="312.34" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1806" + y2="354.63" + id="linearGradient1625" /> + <linearGradient + x1="92.723" + y1="280.78" + gradientTransform="scale(1.1304,0.88467)" + x2="78.425003" + gradientUnits="userSpaceOnUse" + y2="390.64001" + id="linearGradient1543"> + <stop + offset="0" + style="stop-color:#3075a7" + id="stop1545" /> + <stop + offset=".43156" + style="stop-color:#9aadbc" + id="stop1547" /> + <stop + offset=".84995" + style="stop-color:#dce0e3" + id="stop2180" /> + <stop + offset="1" + style="stop-color:#eeeeee" + id="stop1546" /> + </linearGradient> + <linearGradient + id="linearGradient1492"> + <stop + offset="0" + style="stop-color:#dadada" + id="stop1493" /> + <stop + offset=".34923" + style="stop-color:#f1f1f1" + id="stop1496" /> + <stop + offset="1" + style="stop-color:#f0f0f0" + id="stop1494" /> + </linearGradient> + <linearGradient + x1="728.96002" + x2="351.70999" + gradientTransform="matrix(0.28346,0,0,0.31053,-78.835,-40.356)" + y1="230.07001" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1492" + y2="689.85999" + id="linearGradient1495" /> + <linearGradient + x1="741.65002" + x2="622.34998" + gradientTransform="matrix(0.28342,0,0,0.31058,-78.835,-40.356)" + y1="169.44" + gradientUnits="userSpaceOnUse" + xlink:href="#linearGradient1492" + y2="287.73001" + id="linearGradient1497" /> + <linearGradient + x1="687.96002" + y1="236.13" + gradientTransform="matrix(0.29343,0,0,0.29999,-78.835,-40.356)" + x2="330.88" + gradientUnits="userSpaceOnUse" + y2="418.54001" + id="linearGradient1499"> + <stop + offset="0" + style="stop-color:#ffffff" + id="stop1502" /> + <stop + offset="1" + style="stop-color:#ffffff;stop-opacity:0" + id="stop1504" /> + </linearGradient> + <linearGradient + y2="0.0078125" + x1="0.052173998" + x2="0.78261" + y1="0.97656" + id="linearGradient1506"> + <stop + offset="0" + style="stop-color:#000000;stop-opacity:.095506" + id="stop1508" /> + <stop + offset="1" + style="stop-color:#000000;stop-opacity:0" + id="stop1510" /> + </linearGradient> + </defs> + <sodipodi:namedview + id="base" + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1.0" + inkscape:pageopacity="0.0" + inkscape:pageshadow="2" + inkscape:zoom="3.959798" + inkscape:cx="39.47063" + inkscape:cy="24.636392" + inkscape:document-units="mm" + inkscape:current-layer="layer1" + showgrid="true" + inkscape:window-width="1600" + inkscape:window-height="1145" + inkscape:window-x="0" + inkscape:window-y="27" + inkscape:window-maximized="1"> + <inkscape:grid + type="xygrid" + id="grid385" + originx="-73.057513" + originy="-96.385931" /> + </sodipodi:namedview> + <metadata + id="metadata5"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <g + inkscape:label="Layer 1" + inkscape:groupmode="layer" + id="layer1" + transform="translate(-73.057509,-169.30177)"> + <g + id="g374" + transform="matrix(0.01957018,0,0,0.01957018,72.285216,168.62361)"> + <path + id="path372" + d="m 1825.348,1633.382 c -22.034,6.624 -39.107,-14.612 -61.301,-18.376 -12.639,-2.144 -21.588,-58.244 -22.411,-65.671 -3.143,-28.376 -19.957,-52.31 -24.517,-80.109 -0.364,-2.221 -3.308,-5.558 -5.301,-5.746 -39.833,-3.751 -58.618,-35.162 -82.297,-60.916 -39.507,-42.969 -60.961,-96.102 -79.906,-149.078 -13.252,-37.057 -40.534,-63.354 -57.501,-96.883 -65.765,-129.96 -36.757,-64.695 -81.912,-129.694 -93.123,-134.051 3.369,-110.118 -81.515,-189.618 -26.008,-24.358 -72.49,50.844 -82.527,75.762 -21.612,53.658 -54.472,99.887 -92.777,141.464 -225.842,245.134 -181.451,309.623 -300.859,432.831 -34.047,35.13 -63.73,18.797 -91.748,10.355 -11.399,-3.434 -24.298,-11.591 -33.939,-0.132 -12.001,14.264 -26.096,28.34 -17.682,51.402 7.102,19.463 7.139,36.642 -24.76,31.401 -77.476,-12.728 -120.019,0.217 -227.877,-8.136 -19.042,-1.474 -11.938,-15.436 -0.331,-15.112 30.232,0.842 51.329,-19.473 75.485,-32.206 3.344,-1.763 109.811,-58.969 114.821,-66.652 25.747,-39.484 56.793,-75.531 76.691,-118.81 9.813,-21.345 23.222,-40.666 37.542,-58.972 55.32,-70.719 5.969,-77.79 10.893,-289.431 0.517,-22.232 2.402,-44.431 3.016,-66.663 0.648,-23.453 -20.792,-75.045 -22.605,-75.591 -26.513,-7.972 -19.359,-32.249 -23.908,-50.406 C 687.086,634.59 703.874,632.239 707.68,490.462 c 1.152,-42.916 -69.083,-16.171 -85.252,-6.412 -50.572,30.525 -134.74,2.785 -171.748,-38.198 -72.357,-80.13 23.1,-199.372 121.103,-166.988 27.136,8.967 105.141,46.117 109.31,27.716 2.959,-13.061 -13.53,-5.684 -86.802,-37.876 -29.7,-13.049 -62.767,-11.973 -92.462,-24.463 C 451.463,223.056 399.935,204.86 346.698,192.664 290.071,179.692 239.108,150.832 184.308,135.128 140.434,122.556 111.908,94.579 79.737,68.188 48.12,42.25 36.595,41.8 40.054,35.45 c 1.856,-3.407 59.703,3.962 96.003,24.934 72.974,42.16 56.453,23.45 94.719,30.428 62.834,11.457 123.525,30.796 185.113,46.838 81.059,21.114 127.393,-0.364 285.566,50.863 135.873,44.005 455.547,61.679 542.382,209.262 3.755,6.381 8.528,11.502 16.269,13.204 113.329,24.919 268.377,224.068 306.348,411.006 0.805,3.964 11.082,75.206 20.017,85.88 50.757,60.638 55.015,193.615 117.643,285.604 18.725,27.504 26.064,60.955 35.922,92.576 39.335,126.177 59.472,119.63 42.238,137.816 -18.72,19.754 -18.502,44.219 0.241,65.086 18.185,20.245 24.568,73.502 65.758,98.24 16.732,10.048 14.484,22.479 10.142,36.936 -3.556,11.842 -9.571,9.259 -33.067,9.259 z M 835.465,1219.507 c 0.06,4.074 -2.644,9.581 2.635,11.92 11.139,4.934 83.6,-83.724 103.361,-184.854 0.78,-3.991 1.68,-7.801 5.265,-9.969 27.72,-16.759 30.563,-78.379 59.459,-122.875 26.124,-40.228 71.584,-138.249 51.564,-179.757 -9.07,-18.806 -11.243,-37.983 -9.797,-58.187 0.389,-5.43 1.661,-11.85 -5.176,-14.301 -21.136,-7.577 -41.013,-17.572 -65.52,-13.719 -31.338,4.926 -63.45,12.309 -94.751,-3.19 -6.077,-3.009 -19.308,-3.625 -15.692,8.522 11.551,38.802 -40.207,62.434 -16.96,115.191 10.01,22.716 -17.02,26.206 -14.049,44.494 45.816,282.024 -3.311,203.347 -0.339,406.725 z" + inkscape:connector-curvature="0" /> + +</g> + </g> +</svg> diff --git a/ws/Docbook/CustomLayer/webhelp/hdmextensions.xsl b/ws/Docbook/CustomLayer/webhelp/hdmextensions.xsl index db5010e38..cacd6a82a 100644 --- a/ws/Docbook/CustomLayer/webhelp/hdmextensions.xsl +++ b/ws/Docbook/CustomLayer/webhelp/hdmextensions.xsl @@ -59,6 +59,7 @@ <xsl:template match="d:qandaset"> <xsl:variable name="title" select="(d:blockinfo/d:title|d:info/d:title|d:title)[1]"/> + <xsl:variable name="preamble" select="*[local-name(.) != 'title' and local-name(.) != 'titleabbrev' and local-name(.) != 'qandadiv' and local-name(.) != 'qandaentry']"/> <xsl:variable name="toc"> <xsl:call-template name="pi.dbhtml_toc"/> @@ -75,6 +76,8 @@ <xsl:call-template name="id.attribute"> <xsl:with-param name="conditional" select="0"/> </xsl:call-template> + + <img title="Exercise" alt="exercise" style="vertical-align: middle;" width="40em" src="common/images/yoga-exercise.svg"/> <xsl:apply-templates select="$title"/> <xsl:if test="not($title)"> <!-- andhor is output on title if there is one --> diff --git a/ws/Docbook/CustomLayer/webhelp/positioning.css.patch b/ws/Docbook/CustomLayer/webhelp/positioning.css.patch index 1c2ba9025..37556b611 100644 --- a/ws/Docbook/CustomLayer/webhelp/positioning.css.patch +++ b/ws/Docbook/CustomLayer/webhelp/positioning.css.patch @@ -206,7 +206,7 @@ +} + +/* figure frame */ -+.figure { ++.figure, .qandaset { + border-width: 0.5ex; + border-style: solid; + border-color: grey; diff --git a/ws/Docbook/Extensions/Tdata/Common/fig.xml b/ws/Docbook/Extensions/Tdata/Common/fig.xml index 3eb763112..15616014f 100644 --- a/ws/Docbook/Extensions/Tdata/Common/fig.xml +++ b/ws/Docbook/Extensions/Tdata/Common/fig.xml @@ -49,20 +49,6 @@ <question> <para>My first question containing a table:</para> - <informaltable border="1"> - <tr> - <th>Key</th> - - <th>Value</th> - </tr> - - <tr> - <td>b1</td> - - <td>b2</td> - </tr> - </informaltable> - <table border="1" xml:id="testTable"> <caption>Test table</caption> diff --git a/ws/Docbook/Preprocess/Xsl/docbook2html.xsl b/ws/Docbook/Preprocess/Xsl/docbook2html.xsl index 3ff47988c..00b471b64 100644 --- a/ws/Docbook/Preprocess/Xsl/docbook2html.xsl +++ b/ws/Docbook/Preprocess/Xsl/docbook2html.xsl @@ -33,35 +33,34 @@ <title> <xsl:copy-of select="text()|*"/> - <xsl:if test="$slideContainerId"> - <xsl:text> </xsl:text> - - <xsl:variable name="htmlPresentationLinkFileBasename"> - <xsl:text>__figurelink</xsl:text> - <xsl:value-of select="generate-id()"/> - <xsl:text>.html</xsl:text> - </xsl:variable> - - <xsl:variable name="htmlPresentationLinkFilename"> - <xsl:if test="ancestor::*/@xml:base"> - <xsl:call-template name="hdm.get.leftmost.of.separator"> - <xsl:with-param name="path"> - <xsl:value-of select="ancestor::*/@xml:base"/> - </xsl:with-param> - <xsl:with-param name="separator">/</xsl:with-param> - </xsl:call-template> - <xsl:text>/</xsl:text> - </xsl:if> - <xsl:value-of select="$htmlPresentationLinkFileBasename"/> - </xsl:variable> - - <!-- - Hack circumventing docbook XSL bug https://sourceforge.net/p/docbook/bugs/1399 - preventing nesting of <inlinemediaobject> descendants inside <figure>/<title>. - --> - - <xsl:result-document href="target/profile/{$htmlPresentationLinkFilename}" method="html" encoding="utf-8" indent="no"> - <span> + <xsl:variable name="htmlPresentationForumFileBasename"> + <xsl:text>__figurelink</xsl:text> + <xsl:value-of select="generate-id()"/> + <xsl:text>.html</xsl:text> + </xsl:variable> + + <xsl:variable name="htmlPresentationForumFilename"> + <xsl:if test="ancestor::*/@xml:base"> + <xsl:call-template name="hdm.get.leftmost.of.separator"> + <xsl:with-param name="path"> + <xsl:value-of select="ancestor::*/@xml:base"/> + </xsl:with-param> + <xsl:with-param name="separator">/</xsl:with-param> + </xsl:call-template> + <xsl:text>/</xsl:text> + </xsl:if> + <xsl:value-of select="$htmlPresentationForumFileBasename"/> + </xsl:variable> + + <!-- + Hack circumventing docbook XSL bug https://sourceforge.net/p/docbook/bugs/1399 + preventing nesting of <inlinemediaobject> descendants inside <figure>/<title>. + --> + + <xsl:result-document href="target/profile/{$htmlPresentationForumFilename}" method="html" encoding="utf-8" indent="no" + exclude-result-prefixes="#all" xmlns = "http://www.w3.org/1999/xhtml"> + <span> + <xsl:if test="$slideContainerId"> <a> <xsl:attribute name="href"> <xsl:call-template name="slideReference"> @@ -69,23 +68,26 @@ <xsl:with-param name="slideObjectId" select="parent::db:figure/@xml:id"/> </xsl:call-template> </xsl:attribute> - <img style="vertical-align: middle;" src="common/images/presentation.svg" width="30"/> + <img title="Slide presentation" alt="Slide presentation" style="vertical-align: middle;" + src="common/images/presentation.svg" width="40em"/> </a> <xsl:text> </xsl:text> - <!-- Goik: Link to forum --> - <xsl:call-template name="bbComment"> - <xsl:with-param name="elementId" select="parent::db:figure/@xml:id"/> - </xsl:call-template> - </span> - </xsl:result-document> - - <xsl:processing-instruction name="dbhtml-include"> - <xsl:text>href="</xsl:text> - <xsl:value-of select="$htmlPresentationLinkFileBasename"/> - <xsl:text>"</xsl:text> - </xsl:processing-instruction> - - </xsl:if> + </xsl:if> + + <!-- Link to forum --> + <xsl:call-template name="bbComment"> + <xsl:with-param name="elementId" select="parent::db:figure/@xml:id"/> + </xsl:call-template> + </span> + </xsl:result-document> + + <xsl:text> </xsl:text> + + <xsl:processing-instruction name="dbhtml-include"> + <xsl:text>href="</xsl:text> + <xsl:value-of select="$htmlPresentationForumFileBasename"/> + <xsl:text>"</xsl:text> + </xsl:processing-instruction> </title> <xsl:if test="not($slideContainerId) and ends-with(parent::db:figure/db:mediaobject/db:imageobject/db:imagedata/@fileref, '.fig')"> @@ -121,6 +123,60 @@ </xsl:if> </xsl:template> + <xsl:template match="db:qandaset/db:title"> + + <title> + <xsl:copy-of select="text()|*"/> + + <xsl:variable name="htmlPresentationForumFileBasename"> + <xsl:text>__figurelink</xsl:text> + <xsl:value-of select="generate-id()"/> + <xsl:text>.html</xsl:text> + </xsl:variable> + + <xsl:variable name="htmlPresentationForumFilename"> + <xsl:if test="ancestor::*/@xml:base"> + <xsl:call-template name="hdm.get.leftmost.of.separator"> + <xsl:with-param name="path"> + <xsl:value-of select="ancestor::*/@xml:base"/> + </xsl:with-param> + <xsl:with-param name="separator">/</xsl:with-param> + </xsl:call-template> + <xsl:text>/</xsl:text> + </xsl:if> + <xsl:value-of select="$htmlPresentationForumFileBasename"/> + </xsl:variable> + + <!-- + Hack circumventing docbook XSL bug https://sourceforge.net/p/docbook/bugs/1399 + preventing nesting of <inlinemediaobject> descendants inside <figure>/<title>. + --> + + <xsl:message> + <xsl:text>-----------------------------</xsl:text> + <xsl:value-of select="$htmlPresentationForumFilename"/> + </xsl:message> + + <xsl:result-document href="target/profile/{$htmlPresentationForumFilename}" method="html" encoding="utf-8" indent="no" + exclude-result-prefixes="#all" xmlns = "http://www.w3.org/1999/xhtml"> + <span> + <!-- Link to forum --> + <xsl:call-template name="bbComment"> + <xsl:with-param name="elementId" select="parent::db:qandaset/@xml:id"/> + </xsl:call-template> + </span> + </xsl:result-document> + + <xsl:text> </xsl:text> + + <xsl:processing-instruction name="dbhtml-include"> + <xsl:text>href="</xsl:text> + <xsl:value-of select="$htmlPresentationForumFileBasename"/> + <xsl:text>"</xsl:text> + </xsl:processing-instruction> + </title> + </xsl:template> + <xsl:template match="db:imagedata[ends-with(@fileref, '.fig')]"> <xsl:copy> <xsl:attribute name="fileref"> @@ -144,17 +200,17 @@ <xsl:template name="bbComment"> <xsl:param name="elementId"/> <xsl:if test="$topicLookup/map/entry[@id = $elementId]"> - <xsl:variable name="tid" select="$topicLookup/map/entry[@id = $elementId]/@tid"/> - <span class="bbForum" data-tid="$tid"> - <a target="_blank"> - <xsl:attribute name="href"> - <xsl:text>https://bb.mi.hdm-stuttgart.de/topic/</xsl:text> - <xsl:value-of select="$tid"/> - </xsl:attribute> - <img src="common/images/comment.svg" width="20ex" alt="Create comment in forum"/> - <xsl:text> create comment</xsl:text> - </a> - </span> + <xsl:variable name="tid" select="$topicLookup/map/entry[@id = $elementId]/@tid"/> + <span class="bbForum" data-tid="$tid"> + <a target="_blank"> + <xsl:attribute name="href"> + <xsl:text>https://bb.mi.hdm-stuttgart.de/topic/</xsl:text> + <xsl:value-of select="$tid"/> + </xsl:attribute> + <img src="common/images/comment.svg" width="40ex" style="vertical-align: middle;" + alt="Create comment in forum" title="Create comment in forum" /> + </a> + </span> </xsl:if> </xsl:template> -- GitLab