From d5e2afc9eb9351ac2fbddaba7e364aec74f34e9c Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Tue, 23 Jul 2019 16:57:41 +0300 Subject: [PATCH 1/6] At least a quarter of lists completed --- data/osa-3/2-listat.md | 378 ++++++++++++++++++++++++++++++++++------- 1 file changed, 315 insertions(+), 63 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index 9c80ead09..2ad51a6e4 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -1,44 +1,72 @@ --- path: '/osa-3/2-listat' -title: 'Listat' +# title: 'Listat' +title: 'Lists' hidden: false --- - + -- Tunnet listarakenteen ja osaat käyttää listaa osana ohjelmia. -- Tunnet käsitteen indeksi, osaat lisätä arvoja listalle ja osaat hakea tietoa listan indeksistä. -- Osaat käydä listan läpi useammalla erilaisella toistolauseella. -- Osaat tarkistaa onko arvo listalla ja osaat toisaalta poistaa arvoja listalta. -- Tiedät, että lista on viittaustyyppinen muuttuja ja tutustut listan käyttöön metodin parametrina. + + + + +- You are familiar with the list structure and can use it in your programs + +- You are familiar with the concept of index, you can add values to a list, and you know how to retrieve information from a list's indices + +- You can use several kinds of looping statements to iterate over a list + +- You know how to check if a value exists in a list, and you can remove values from a list + +- You are aware that a list is a reference-type variable, and you will familiarize yourself with using lists as method parameters -Ohjelmoidessa tulee vastaan tilanteita, joissa haluamme käsitellä useita arvoja. Epäkäytännöllinen mutta tähän mennessä käytännössä ainoa tapa on ollut määritellä jokaiselle arvolle oma muuttuja. + +We often encounter situations that call for handling of multiple values when programming. Before this, the practically only means available to us has been to define a separate variable for storing each value. This method can easily become impractical. -```java + + + +```java +String word1; +String word2; +String word3; +// ... +String word10; ``` -Yllä esitetty ratkaisu on oikeastaan kelvoton -- ajattele ylläoleva esimerkki vaikkapa tuhannella sanalla. + -Ohjelmointikielet tarjoavat apuvälineitä, joiden avulla on helppo säilyttää useita arvoja. Tutustumme seuraavaksi Java-ohjelmointikielen ehkäpä eniten käytettyyn apuvälineeseen [ArrayListiin](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html), joka on useamman samankaltaisen arvon säilömiseen tarkoitettu lista. +The solution presented above is frankly useless -- consider the situation when there are thousands of words to store. -ArrayList on Javan valmiiksi tarjoama työväline listojen käsittelyyn. Se tarjoaa metodit muunmuassa arvojen lisäämiseen listalle, arvojen poistamiseen listalta sekä arvojen hakemiseen tietystä listan kohdasta. Listan konkreettinen toiminta -- eli miten lista on oikeasti ohjelmoitu -- on abstrahoitu metodien taakse, jolloin listaa käyttävän ohjelmoijan ei tarvitse välittää listan sisäisestä toiminnallisuudesta. + +Programming languages offer tools to assist in storing a number of values. We will next take a peek at perhaps the most used single tool the Java language, the [ArrayList](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html), which is used for storing many values of the same type. -## Listan käyttöönotto ja luominen + -Jotta ArrayListiä voi käyttää, tulee se tuoda ohjelman käyttöön. Tämä onnistuu kirjoittamalla ohjelman ylälaitaan komento `import java.util.ArrayList;`. Alla on esimerkkiohjelma, missä ArrayList tuodaan ohjelman käyttöön. +ArrayList is a premade tool to help in handling lists. It offers methods for, among others, adding values to the list, removing values from the list, and getting a value from a specific place in the list. The concrete operation -- how the list is concretely programmed -- has beed abstracted behind these methods, so a programmer who uses a list need not concern themselves with its inner workings. -```java + + +## Beginning to use lists and creating them + + + +In order to use ArrayList it must be imported in the program. This happens by writing the command `import java.util.ArrayList;` to the top of the program. In the example below ArrayList is imported into the program. + + + +```java +// import the list so the program can use it +import java.util.ArrayList; + +public class Program { + + public static void main(String[] args) { + // the list isn't used yet + } +} ``` -Listan luominen tapahtuu sanomalla "`ArrayList lista = new ArrayList<>()`", missä _Tyyppi_ on listalle säilöttävien arvojen tyyppi, eli esimerkiksi `String`. Alla olevassa esimerkissä luodaan merkkijonojen säilömiseen tarkoitettu lista. + +Creating a new list is done with the command `ArrayList list = new ArrayList<>()`, where _Type_ is the type of the values to be stored in the list (e.g. `String`). We create a list for storing integers in the example below. -```java + + + +```java +// import the list so the program can use it +import java.util.ArrayList; + +public class Program { + + public static void main(String[] args) { + // create a list + ArrayList list = new ArrayList<>(); + + // the list isn't used yet + } +} ``` -ArrayList-muuttujan tyyppi on `ArrayList`. Listamuuttujaa esiteltäessä muuttujan tyypin lisäksi listalle määritellään siihen säilöttävien arvojen tyyppi -- **kaikki samalle listalle lisättävät arvot ovat saman tyyppisiä**. Esimerkiksi merkkijonoja sisältävän ArrayListin tyyppi on `ArrayList` ja kokonaislukuja sisältävän ArrayListin tyyppi on `ArrayList`. Listan luominen tapahtuu komennolla `new ArrayList<>();`. + +The type of the `list` variable is `ArrayList`. When introducing a list variable, it is important to define also the type of the values to be stored, and not only the type of the list variable itself. **All the variables stored in one list have the same type**. The type of an ArrayList that stores strings is therefore `ArrayList`. A new list is created with the command `new ArrayList<>();`. -## Listan sisältämien arvojen tyypin määrittely -Listan sisältämien arvojen tyyppien määrittelyssä muuttujista tulee käyttää niiden "isolla kirjaimella kirjoitettuja" versioita. Esimerkiksi int-tyyppisiä muuttujia sisältävä lista tulee määritellä muodossa `ArrayList` ja double-tyyppisiä muuttujia sisältävä lista tulee määritellä muodossa `ArrayList`. + -Tämä liittyy siihen, miten ArrayList on toteutettu. Javan muuttujat voidaan jakaa kahteen kategoriaan: alkeistyyppisiin muuttujiin ja viittaustyyppisiin muuttujiin. **Alkeistyyppiset** muuttujat kuten `int` ja `double` sisältävät niihin liittyvät arvot. **Viittaustyyppiset** muuttujat taas, kuten esimerkiksi `ArrayList` sisältävät viitteen paikkaan, joka sisältää muuttujaan liittyvät arvot. +## Defining the type of values that a list can store -Alkeistyyppiset muuttujat pystyvät sisältämään vain rajatun määrän tietoa, kun taas viitteen taakse tietoa voi säilöä lähes rajattomasti. + -Alla on kuvattuna eri tyyppisiä arvoja sisältävien listojen luominen. +When defining the type of values that a list include, the "capitalized first letter" versions of types must be used. A list that includes int-type variables has to be defined in the form `ArrayList`; a list that includes double-type variables similarly in the form `ArrayList`. -```java + + +The reason for this practice relates to the implementation of ArrayList. The variables in Java can be divided into two categories: value type (primitive) and reference type (reference type) variables. **Value type** variables such as `int` or `double` contain their values directly. **Reference type** variables such as `ArrayList`, in contrast, contain a reference to the location that contains the value(s) relating to that variable. + + + +Value type variables can hold a very limited amount of information, whereas references can be used to store a near limitless amount. + + + +Below are examples of creating lists that contain different types of values. + + ```java +ArrayList list = new ArrayList<>(); +list.add(1); +``` + + + +```java +ArrayList list = new ArrayList<>(); +list.add(4.2); ``` -```java + ```java +ArrayList list = new ArrayList<>(); +list.add(true); +``` + + + +```java +ArrayList list = new ArrayList<>(); +lista.add("String is a reference type variable"); ``` -Kun lista on luotu, ArrayList olettaa, että sen sisältämät muuttujat ovat viittaustyyppisiä. Java muuntaa automaattisesti `int`-tyyppisen muuttujan `Integer`-tyyppiseksi kun se lisätään listalle, sama tapahtuu myös kun muuttuja haetaan listalta. Vastaava muunnos tapahtuu myös `double`-tyyppiselle muuttujalle, josta tulee `Double`-tyyppinen muuttuja. Tämä tarkoittaa sitä, että vaikka lista määritellään `Integer`-tyyppisiä arvoja sisältäväksi, voi siihen lisätä `int`-tyyppisiä arvoja. + -```java +Once a list is created, ArrayList assumes that all the variables in it are reference type. Java automatically converts an `int` type variable into `Integer` type when it is being added to a list, and the same occurs when a variable is retrieved from a list. The same conversion occurs to `double` type variables, which are converted to `Double`. In practice the result is that even though a list is defined to contain variables of type `Integer`, `int` type variables can also be added to it. + + + + +```java +ArrayList integers = new ArrayList<>(); +int integer = 1; +integers.add(integer); + +ArrayList doubles = new ArrayList<>(); +double d = 4.2; +doubles.add(d); ``` -Palaamme teemaan jatkossakin, sillä tämä jako alkeis- ja viittaustyyppisiin muuttujiin vaikuttaa ohjelmiimme myös muilla tavoin. + +We will return to discuss this matter of value and reference type variables, since the division has other effects on our programs, too. -## Listalle lisääminen ja tietystä kohdasta hakeminen + -Seuraavassa esimerkissä esitellään merkkijonoja säilövä ArrayList, johon lisätään muutama merkkijono. Lisääminen tapahtuu listan metodilla `add`, jolle annetaan parametrina listalle lisättävä arvo. Tämän jälkeen tulostetaan listan nollannessa kohdassa oleva arvo. Listan tietystä kohdasta haetaan arvo listan metodilla `get`, jolle annetaan parametrina kokonaislukutyyppinen arvo, joka kertoo kohdan mistä arvo haetaan. +## Adding to a list and retrieving a value from a specific place -Listan metodeja kutsutaan kirjoittamalla ensin listaa kuvaavaan muuttujan nimi, sitten piste, ja sitten metodin nimi. + -```java +The next example shows adding a few string into an ArrayList that contains string. Adding is done with the list method `add`, which takes the value to be added as a parameter. Then we print the value at position zero. To retrieve a value from a certain position, you use the list method `get`, which is given the place of retrieval as a parameter. + + + +To call a list method you first write the name of the variable that describes the list, followed by a dot and the name of the method. + + + + +```java +// import list so that the program can use it +import java.util.ArrayList; + +public class WordListExample { + + public static void main(String[] args) { + // create the word list for storing strings + ArrayList wordList = new ArrayList<>(); + + // add two values to the word list + wordList.add("First"); + wordList.add("Second"); + + // retrieve the value from position 0 of the word list, and print it + System.out.println(wordList.get(0)); + } +} ``` - + + + + +First + -Kuten huomaat, metodilla `get` saa listan ensimmäisen arvon kun metodille antaa parametrina arvon `0`. Tämä johtuu siitä, että **listan kohtien laskeminen alkaa nollasta**. Listan ensimmäinena arvo löytyy kutsulla `sanalista.get(0)`, listan toinen arvo kohdasta `sanalista.get(1)` jne. + +As you can see, the `get` method retrieves the first value from the list when it is given the parameter `0`. This is explained by that **counting positions in a list starts from zero**. The first value is found by `wordList.get(0)`, the second by `wordList.get(1)`, etc. -```java + + + +```java +import java.util.ArrayList; + +public class WordListExample { + + public static void main(String[] args) { + ArrayList wordList = new ArrayList<>(); + + wordList.add("First"); + wordList.add("Second"); + + System.out.println(wordList.get(1)); + } +} ``` - + + + + +Second + - + + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä merkkijonoja ja lisää niitä listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää tyhjän merkkijonon. Ohjelma tulostaa tämän jälkeen listan ensimmäisen arvon. + +The exercise contains a base that asks the user for strings and adds them to a list. The program stops reading when the user enters an empty string. The program then prints the first value on the list. -Muokkaa ohjelmaa siten, että ensimmäisen arvon sijaan tulostetaan kolmas arvo. Huomaa, että ohjelmoijat aloittavat laskemisen nollasta! Ohjelma saa rikkoutua mikäli listalla ei ole vähintään kolmea arvoa, eli tällaiseen tilanteeseen ei tarvitse varautua millään tavalla. + + +Your assignment is to modify the program so that instead of the first value, the third value on the list is printed. Remember that programmers start counting from zero! The program is allowed to malfunction if there are fewer than three entries on the list, so you don't need to prepare for such an event at all. - + + +**Tom** +**Emma** +**Alex** +**Mary** + +Alex + + + + + + + +**Emma** +**Alex** +**Mary** + +Mary + - + + + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä kokonaistyyppisiä lukuja ja lisää niitä listalle. Lukeminen lopetetaan kun käyttäjä syöttää luvun 0. Ohjelma tulostaa tämän jälkeen listan ensimmäisen arvon. + +In the exercise template there is a program that reads integers from the user and adds them to a list. The user entering the number 0 ends this. The program then prints the first value on the list. -Muokkaa ohjelmaa siten, että listan ensimmäisen arvon sijaan ohjelma tulostaa listan toisen ja kolmannen arvon summan. Ohjelma saa rikkoutua mikäli listalla ei ole vähintään kolmea arvoa, eli tällaiseen tilanteeseen ei tarvitse varautua millään tavalla. + + +Modify the program so that instead of the first value the program prints the sum of the second and third numbers. The program is allowed to malfunction if there are fewer than three entries on the list, so you don't need to prepare for such an event at all. @@ -249,12 +440,16 @@ Muokkaa ohjelmaa siten, että listan ensimmäisen arvon sijaan ohjelma tulostaa -### Tiedon hakeminen "olemattomasta" kohdasta + -Jos ArrayListiltä haetaan arvoa kohdasta, jota listalla ei ole, tulostaa ohjelma virheen `IndexOutOfBoundsException`. Alla olevassa esimerkissä on ohjelma, missä listalle lisätään kaksi arvoa, jonka jälkeen yritetään tulostaa arvoa listan kohdasta kaksi. +## Retrieving information from a "nonexistent" place + -```java +If you try to retrieve information from a place that the list doesn't have, the program prints the error `IndexOutOfBoundsException`. In the example below two values are added to a list, after which there is an attempt to print the value at place two on the list. + + + + +```java +import java.util.ArrayList; + +public class Example { + + public static void main(String[] args) { + ArrayList wordList = new ArrayList<>(); + + wordList.add("First"); + wordList.add("Second"); + + System.out.println(wordList.get(2)); + } +} ``` -Koska listalla olevien arvojen numerointi eli **indeksöinti** alkaa nollasta, ei ohjelma löydä arvoa kohdasta kaksi ja ohjelman suoritus päättyy virhetilanteeseen. Alla on kuvattuna yllä olevan ohjelman suorituksen aiheuttama virheviesti. + + +Since zero is the first value used in numbering the places (i.e. **indexing**), the program doesn't find anything at place two and its execution ends with an error. Below is captioned the error message caused by the program. @@ -283,39 +496,55 @@ Koska listalla olevien arvojen numerointi eli **indeksöinti** alkaa nollasta, e -Virheviesti antaa myös pientä vinkkiä ArrayList-olion kapseloimasta toteutuksesta. Se kertoo metodit, joita kutsuttaessa virhe tapahtui. Ensin ohjelmassa on kutsuttu ?`main`-metodia. Tämän jälkeen main-metodissa on kutsuttu ArrayListin `get`-metodia. Tämän jälkeen ArrayListin `get`-metodissa on kutsuttu ArrayListin `rangeCheck`-metodia, jossa virhe tapahtuu. Tässä on myös hyvä esimerkki metodien nimennästä. Vaikka emme olekaan ennen kuulleet metodista `rangeCheck`, voimme arvata, että se tarkastaa onko haettu kohta jollain halutulla alueella. Virhe johtunee siitä, että näin ei ollut. + + +The error message also hints at the capsulated implementation of an ArrayList object. It lists the methods that were called when the error occured. First the program called the `main` method. Then the main method called the `get` method of ArrayList. After this the `get` method in ArrayList called the `rangeCheck` method, in which the error occurred. This is also an instance of good naming of methods. Despite never hearing of the method `rangeCheck`, we can with good reason guess that it checks if a place is contained in the wanted range. The error likely occurred because this was not the case. -Lista on erittäin hyödyllinen kun halutaan säilöä muuttujien arvoja myöhempää käsittelyä varten. Sillä on myös helpohko tehdä virheitä. + -Tehtäväpohjassa on listaa käyttävä ohjelma. Muokkaa ohjelmaa siten, että sen suorittaminen tuottaa aina virheen `IndexOutOfBoundsException`. Ohjelman tulee olla sellainen, että käyttäjän ei tarvitse antaa koneelle syötettä (esim. näppäimistöltä). +A list is very useful for storing variables for later use. Making mistakes is also easy with lists. + -Ohjelmassa näkyy myös tapa listan läpikäyntiin -- palaamme tähän tapaan myöhemmin. +There is a program that uses a list in the exercise template. Modify it so that its execution always produces the error `IndexOutOfBounds`. The user should not have to give any inputs to the program (e.g. write something on the keyboard). + + + + +You can also see a means for going through the values of a list -- we will return to this topic a bit later. + + + - -Listan paikkojen numerointi eli indeksöinti alkaa aina nollasta. Listan ensimmäinen arvo on indeksissä 0, toinen arvo indeksissä 1, kolmas arvo indeksissä 2 ja niin edelleen. Ohjelmissa indeksiä merkitään usein yksinkertaisesti muuttujalla nimeltä `i`. + + +Numbering places i.e. indexing always begins with zero. The list's first value is located at index 0, the second value at index 1, the third value at index 2, and so on. In programs an index is denoted with a variable called `i`.
-Ylläolevassa listassa ensimmäisenä on arvo 6 ja toisena arvo 1. Jos ylläolevaan listaan lisättäisiin uusi arvo kutsumalla `luvut`-listan metodia `add` parametrilla 8, menisi luku 8 listan indeksiin 6 eli seitsemänneksi luvuksi. + + +In the list above the first value is 6 and the second value 1. If a new value were added to the list by calling the `add` method of `numbers` with 8 as parameter, the number 8 would be placed at index 6. It would be the seventh number in the list.
-Vastaavasti kutsumalla metodia `get` parametrilla 4, listalta haettaisiin viidettä lukua. + + +Similarly, by calling the method `get` with the parameter 4, the fifth number in the list would be retrieved.
@@ -323,13 +552,18 @@ Vastaavasti kutsumalla metodia `get` parametrilla 4, listalta haettaisiin viidet - + + -Jokaisella Javan tarjoamalla työvälineellä on nimi ja sijainti. Valmiin työvälineen tuominen ohjelman käyttöön tapahtuu `import`-käskyllä. Käskylle kerrotaan luokan sijainti ja luokan nimi. Esimerkiksi ArrayListin käyttöönotto vaatii komennon `import java.util.ArrayList;` ohjelman ylälaitaan. -```java + + +Each tool offered by Java has a name and location. The program can use a tool after it has been imported with the `import` command. The command is given the location and the name of the wanted class. For example,using ArrayList necessitates placing the command `import java.util.ArrayList;` to the top of the program. + + + + +```java +import java.util.ArrayList; + +public class ListProgram { + + public static void main(String[] args) { + ArrayList wordList = new ArrayList<>(); + + wordList.add("First"); + wordList.add("Second"); + } +} ``` -Sama pätee myös muillekin Javan luokille. Olemmekin jo aiemmin käyttäneet lukemiseen tarkoitettua Scanner-luokkaa, jonka on saanut käyttöön komennolla `import java.util.Scanner;` + + + +The same is generally true for all Java classes. Indeed, we have already used the Scanner class used to read input earlier. To use it we have included the command `import java.util.Scanner;`. -Useamman apuvälineen käyttöönotto on helppoa. Käyttöön tuotavat apuvälineet listataan allekkain ohjelman ylälaitaan. + +Taking advantage of multiple tools is straighforward. The tools to be imported are listed at the top of the program. ```java import java.util.ArrayList; From 06596777ae5d6b55bca1c55fb523cabbe0c043b1 Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Tue, 23 Jul 2019 18:11:16 +0300 Subject: [PATCH 2/6] Halfway done with the lists --- data/osa-3/2-listat.md | 242 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 217 insertions(+), 25 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index 2ad51a6e4..91f195c73 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -601,7 +601,7 @@ The same is generally true for all Java classes. Indeed, we have already used th Taking advantage of multiple tools is straighforward. The tools to be imported are listed at the top of the program. -```java + + +```java +import java.util.ArrayList; +import java.util.Scanner; + +public class ListProgram { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + ArrayList wordList = new ArrayList<>(); + + sanalista.add("First"); + sanalista.add(scanner.nextLine()); + } +} ``` -## Listan läpikäynti + +## Going through a list -Tarkastellaan seuraavaksi menetelmiä listan läpikäyntiin. Aloitetaan suoraviivaisella esimerkillä neljä arvoa sisältävän listan tulostamiseen. Alla listalle lisätään neljä nimeä, jonka jälkeen listan sisältö tulostetaan. + +Next we will examine methods that can be used to go through the values of a list. Let's start with a simple example where we print a list containing four values. -```java + + + +```java +ArrayList teachers = new ArrayList<>(); + +teachers.add("Simon"); +teachers.add("Samuel"); +teachers.add("Ann"); +teachers.add("Anna"); + +System.out.println(teachers.get(0)); +System.out.println(teachers.get(1)); +System.out.println(teachers.get(2)); +System.out.println(teachers.get(3)); ``` - + + + + +Simon +Samuel +Ann +Anna + -Esimerkki on kömpelö. Entä jos listalla olisi enemmän arvoja? Tai vähemmän? Entäs jos emme tietäisi listalla olevien arvojen määrää? + +The example is obviously cumbersome. What if there were more values on the list? Or fewer? How about if we didn't know the number of values on the list? -Listalla olevien arvojen lukumäärän saa selville listan tarjoamalla metodilla **size**, joka palauttaa listalla olevien arvojen lukumäärän. Lukumäärä on kokonaisluku (`int`) ja sitä voidaan käyttää osana lauseketta tai se voidaan asettaa kokonaislukumuuttujaan myöhempää käyttöä varten. + +The number of values on a list is provided by the list method **size** that returns the number in question. The number is an integer (`int`), and it can be used as a part of an expression or stored in an integer variable for later use. -```java + + + +```java +ArrayList list = new ArrayList<>(); +System.out.println("Number of values on the list: " + list.size()); + +lista.add("First"); +System.out.println("Number of values on the list: " + list.size()); + +int values = list.size(); + +lista.add("Second"); +System.out.println("Number of values on the list: " + values); ``` - + + + + + +Number of values on the list: 0 +Number of values on the list: 1 +Number of values on the list: 1 + + - + -Tehtäväpohjassa on ohjelma, joka lukee käyttäjältä syötteitä. Muokkaa ohjelman toimintaa siten, että kun syötteiden lukeminen lopetetaan, ohjelma tulostaa listalla olevien arvojen lukumäärän. + + +In the exercise template there is a program that reads input from the user. Modify its operating so that when the program quits reading, the program prints the number of the values on the list. - + + + + + +**Tom** +**Emma** +**Alex** +**Mary** + +In total: 4 + - + + + + +**Juno** +**Elizabeth** +**Mason** +**Irene** +**Olivia** +**Liam** +**Ida** +**Christopher** +**Mark** +**Sylvester** +**Oscar** + +In total: 11 + -Huom! Käytä tässä listan valmiiksi tarjoamaa metodia `size`. + + +N.B.! Be sure to make the `size` method of the list. -### Listan läpikäynti + -Tehdään aiemmasta kunkin indeksin manuaalisesti tulostavasta ohjelmasta uusi versio. Tässä välivaiheen versiossa pidetään tulostettavasta paikasta kirjaa muuttujan `indeksi` avulla: +## Going through a list, vol 2 + -```java +Let's make a new version of the program that prints each index manually. In this example under construction we use the variable `index` to keep track of the place we use for printing. + + + + +```java +ArrayList teachers = new ArrayList<>(); + +opettajat.add("Simon"); +opettajat.add("Samuel"); +opettajat.add("Ann"); +opettajat.add("Anna"); + +int index = 0; + +if (index < teachers.size()) { + System.out.println(teachers.get(index)); // index = 0 + index = index + 1; // index = 1 +} + +if (index < teachers.size()) { + System.out.println(teachers.get(index)); // index = 1 + index = index + 1; // index = 2 +} + +if (index < teachers.size()) { + System.out.println(teachers.get(index)); // index = 2 + index = index + 1; // index = 3 +} + +if (index < teachers.size()) { + System.out.println(teachers.get(index)); // index = 3 + index = index + 1; // index = 4 +} + +if (index < index.size()) { + // this will not be executed since index = 4 and teachers.size() = 4 + System.out.println(teachers.get(index)); + index = index + 1; +} ``` + -Huomaamme, että ylläolevassa ohjelmassa on toistoa. +We notice slight repetition in the program above. -Voimme muuttaa `if`-lauseet `while`:ksi, jota toistetaan kunnes ehto `indeksi < opettajat.size()` ei enää päde (eli muuttujan `indeksi` arvo kasvaa liian suureksi). + -```java +We can turn the `if` statements into a `while` that is repeated until the condition `index < teachers.size()` no longer holds (i.e. the value of the variable `index` grows too great). + + + +```java +ArrayList teachers = new ArrayList<>(); + +teachers.add("Simon"); +teachers.add("Samuel"); +teachers.add("Ann"); +teachers.add("Anna"); + +int index = 0; +// Repeat for as long as the value of the variable `index` +// is smaller than the size of the teachers list +while (index < teachers.size()) { + System.out.println(teachers.get(index)); + index = index + 1; +} ``` -Nyt tulostus toimii riippumatta listalla olevien alkioiden määrästä. -Aiemmin tarkastelemamme for-toistolause, jota käytetään kun läpikäytäviä arvoja on tietty määrä, on tähän erittäin näppärä. Voimme muuttaa ylläolevan toistolauseen `for`-toistolauseeksi, jolloin ohjelma näyttää seuraavalta. + -```java +With this method the printing works regardless of the number of elements. + + + +For repeat statement is used for going through a specific number of values, as we previousy learned. It comes in very handy with lists. We ca nturn the repeat statement above to use `for`, after which the program looks like this. + + + +```java +ArrayList opettajat = new ArrayList<>(); + +teachers.add("Simon"); +teachers.add("Samuel"); +teachers.add("Ann"); +teachers.add("Anna"); + +for (int index = 0; index < teachers.size(); index++) { + System.out.println(teachers.get(index)); +} ``` - + + + + +Simon +Samuel +Ann +Anna + -Tyypillisesti for-toistolauseilla indeksimuuttujan nimi on `i`: + + +Typically, the index variable of the for loop is called `i`: ```java for (int i = 0; i < opettajat.size(); i++) { From c618291619bcae64354c6e59e94098ac18fb57d4 Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Wed, 24 Jul 2019 13:59:32 +0300 Subject: [PATCH 3/6] A few exercises more done --- data/osa-3/2-listat.md | 215 +++++++++++++++++++++++++++++++++++------ 1 file changed, 187 insertions(+), 28 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index 91f195c73..8c5c9f284 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -1003,16 +1003,24 @@ Anna Typically, the index variable of the for loop is called `i`: -```java + + +```java +for (int i = 0; i < teachers.size(); i++) { + System.out.println(teachers.get(i)); +} ``` -Tarkastellaan seuraavaksi listan käyttöä kokonaisluvuilla. Toiminnallisuus ei poikkea juurikaan edellisestä esimerkistä. Suurimmat erot liittyvät listan luomiseen -- listan sisältämien arvojen tyypiksi määritellään `Integer` ja listaa kuvaavan muuttujan nimeksi asetetaan `luvut`. Tämän lisäksi listalta get-metodilla haettava arvo asetetaan muuttujaan `luku` ennen tulostusta. + +Let's then examine using a list to store integers. The functionality is largely the same as in the previous example. The greatest difference is in creating the list -- the type of stored values is defined as `Integer`, and the value to be printed is stored in the variable called `number` before printing. -```java + + + +```java +ArrayList numbers = new ArrayList<>(); + +numbers.add(1); +numbers.add(2); +numbers.add(3); +numbers.add(4); + +for (int i = 0; i < numbers.size(); i++) { + int number = numbers.get(i); + System.out.println(number); + // alternatively: System.out.println(nubers.get(i)); +} ``` @@ -1037,10 +1060,12 @@ for (int i = 0; i < luvut.size(); i++) { -Listalla olevien arvojen tulostaminen käänteisessä järjestyksessä olisi myös suoraviivaista. + +Printing the numbers in the list in reverse order would also be simple. -```java + + + +```java +ArrayList numbers = new ArrayList<>(); + +numbers.add(1); +numbers.add(2); +numbers.add(3); +numbers.add(4); + +int index = numbres.size() - 1; +while (index >= 0) { + int number = numbers.get(index); + System.out.println(number); + index = index - 1; +} ``` @@ -1067,29 +1108,44 @@ while (indeksi >= 0) { -Alla oleva ohjelma visualisoi ohjelman suorituksen. Visualisaatio ei kuitenkaan näytä ArrayListin sisäistä tilaa (eli sen sisältämiä arvoja). + + +The execution of the program is visualized below. However, the visualization does not show the internal state of the ArrayList (i.e. the values contained by it). + + - + -Kokeile saisitko edellisen esimerkin tehtyä myös for-toistolauseella! + +Try and recreate the previous example with the for loop! - + -Seuraavissa tehtävissä harjoitellaan listan ja indeksin käyttöä. Vaikka pystyisit tekemään tehtävät ilman listaa, keskity tehtävissä listan käytön harjoitteluun. Tehtävissä toivottu toiminnallisuus tulee toteuttaa lukujen lukemisen jälkeen. + + + + +The next exercises are meant for learning to use lists and indices. Even if you could complete the execises without a list, concentrate on training to use it. The functionality in the exercises is to be implemented after reading the input numbers. - + -Tehtäväpohjassa on ohjelma, joka lukee käyttäjältä syötteitä ja lisää syötteet listalle. Syötteen lukeminen lopetetaan kun käyttäjä syöttää tyhjän merkkijonon. + -Muokkaa ohjelmaa siten, että kun syötteiden lukeminen lopetetaan, ohjelma tulostaa viimeksi luetun arvon. Tulosta viimeksi luettu arvo listalta. Käytä tässä hyödyksi listan koon kertovaa metodia. + - +In the exercise template there is a program that reads inputs from the user and adds them to a list. Reading is stopped once the user enters an empty string. + + + +Your task is to modify the method to print the last read value after it stops reading. Print the value that was read last from the list. Use the method that tells the size of a list to help you. + + +**Tom** +**Emma** +**Alex** +**Mary** + +Mary + + + + + + + +**Juno** +**Elizabeth** +**Mason** +**Irene** +**Olivia** +**Liam** +**Ida** +**Christopher** +**Mark** +**Sylvester** +**Oscar** + +Oscar + - + -Tehtäväpohjassa on ohjelma, joka lukee käyttäjältä syötteitä ja lisää syötteet listalle. Syötteen lukeminen lopetetaan kun käyttäjä syöttää tyhjän merkkijonon. + -Muokkaa ohjelmaa siten, että kun syötteiden lukeminen lopetetaan, ohjelma tulostaa sekä ensiksi että viimeksi luetun arvon. Voit olettaa, että listalle luetaan vähintään kaksi arvoa. + - +In the exercise template there is a program that reads inputs from the user and adds them to a list. Reading is stopped once the user enters an empty string. + + + +Modify the program to print both the first and the last values after the reading ends. You may suppose that at least two values are read into the list. + + + +**Tom** +**Emma** +**Alex** +**Mary** + +Tom +Mary + -**Juno** + + + + +**Juno** +**Elizabeth** +**Mason** +**Irene** +**Olivia** +**Liam** +**Ida** +**Christopher** +**Mark** +**Sylvester** +**Oscar** + +Juno +Oscar + - + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Lisää ohjelmaan toiminnallisuus, joka lukujen lukemisen jälkeen tulostaa käyttäjän syöttämät luvut. Syötteen lukemisen päättämisestä ilmoittavaa lukua ei tulosteta. + + +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + + +Expand the functionality of the program so that after reading the numbers, it prints all the numbers received from the user. The number used to indicate stopping should not be printed. @@ -1187,12 +1312,16 @@ Lisää ohjelmaan toiminnallisuus, joka lukujen lukemisen jälkeen tulostaa käy - + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Lisää ohjelmaan toiminnallisuus, joka lukujen lukemisen jälkeen kysyy käyttäjältä alkuindeksiä ja loppuindeksiä. Tämän jälkeen ohjelman tulostaa listalla olevat luvut käyttäjän syöttämien indeksien välillä. Voit olettaa, että käyttäjä syöttää indeksit, jotka löytyvät listalta. +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + +Expand the program to ask for a start and end indices once it has finished asking for numbers. After this the program shall prints all the numbers in the list that fall in the specified range (between the indices given by the user, inclusive). You may assume that the user gives indices that match some numbers in the list. + + @@ -1216,12 +1346,41 @@ Mihin? **2** **11** **-1** +From where? **1** +To where? **2** +2 +8 + + + + + + + +**72** +**2** +**8** +**11** +**-1** + +From where? **0** +To where? **2** +72 +2 +8 + From 7070d128545a9b2437e3dd60c36bff613e8d668b Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Thu, 25 Jul 2019 10:36:36 +0300 Subject: [PATCH 4/6] Saving if the fire consumes the laptop --- data/osa-3/2-listat.md | 192 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 170 insertions(+), 22 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index 8c5c9f284..ca7679ac2 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -1386,13 +1386,20 @@ To where? **2** - + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Lisää ohjelmaan toiminnallisuus, joka lukujen lukemisen jälkeen etsii listalta listan suurimman luvun ja tulostaa sen arvon. Ohjelman pitäisi toimia seuraavasti. - + + +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + + +Continue developing the program so that it ends the greatest number in the list and prints its value after reading all the numbers. The programming should work in the following manner. + + + + + +**72** +**2** +**8** +**93** +**11** +**-1** + +The greatest number in the list: 93 + -Ota mallia allaolevasta pienintä lukua etsivästä lähdekoodista. -```java + + +You can use the source code below as an inspitation. It is used to find the smallest number. + + + +```java +// assume we have a list that contains integers + +int smallest = list.get(0); + +for(int i = 0; i < list.size(); i++) { + int number = list.get(i); + if (smallest > number) { + smallest = number; + } +} + +System.out.println("The smallest number: " + smallest); ``` - + -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Lisää ohjelmaan toiminnallisuus, joka kysyy käyttäjältä lukua ja kertoo luvun indeksin. Mikäli lukua ei löydy, ohjelman ei tule kertoa siitä. - + + +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + + +Expand the program that then asks the user for a number, and reporst that number's index in the list. If the number is not found, the program should not print anything. + + @@ -1454,21 +1499,54 @@ Luku 2 on indeksissä 1 **11** **-1** +What number is searched for? **2** +Number 2 is at index 1 + + + + + + + +**72** +**2** +**8** +**8** +**11** +**-1** + +What number is searched for? **8** +Number 8 is at index 2 +Number 8 is at index 3 + - + -Toteuta ohjelma, joka lukee käyttäjältä lukuja. Kun käyttäjä syöttää luvun 9999, lukujen lukeminen lopetetaan. Ohjelma tulostaa tämän jälkeen pienimmän listalla olevan luvun sekä indeksit, joista pienin luku löytyy. Pienin luku voi siis esiintyä useamman kerran. + + - +Write a program that reads numbers from the user. When number 9999 is entered, the reading process stops. After this the program will print the smallest number in the list, and also the indices where that number is found. Notice: the smallest number can appear multiple times in the list. + + + +**72** +**2** +**8** +**8** +**11** +**9999** + +The smallest number is 2 +The smallest number is found at index 1 + + + + + + + +**72** +**44** +**8** +**8** +**11** +**9999** + + +The smallest number is 8 +The smallest number is found at index 2 +The smallest number is found at index 3 + -Vihje: yhdistele tässä tehtävissä "Listan suurin luku" ja "Kysytyn luvun indeksi" harjoittelemiasi ohjelmia. Etsi ensin pienin luku, ja etsi tämän jälkeen pienimmän luvun indeksi. + + +Hint: combine the programs you wrote for the exercises "Greatest number in the list" and "Index of the requested number". First find the smalleest number, and then find the index of that number. -### Listan läpikäynti for-each -toistolauseella + -Mikäli listan arvojen läpikäynnissä ei tarvita tietoa indeksistä, voi listan läpikäyntiin käyttää **for-each** -toistolausetta. Se poikkeaa aiemmin käyttämistämme toistolauseista, sillä siinä ei ole erillistä toisto- tai kasvatusehtoa. +## Going through a list with a for each repeat statement + -```java +If you don't need information about the index when going through the values of a list, you can use the **for each** loop for the purpose. It differs from the previous repeat statements in that id has no separate condition for repeating or incrementing. + + + + +```java +ArrayList teachers = new ArrayList<>(); + + +teachers.add("Simon"); +teachers.add("Samuel"); +teachers.add("Ann"); +teachers.add("Anna"); + +for (String teacher: teachers) { + System.out.println(teacher); +} ``` -Yllä kuvattu for-each toistolause käytännössä piilottaa osan aiemmin harjoittelemastamme for-toistolauseesta. Edellä kuvattu for-each toistolause näyttäisi for-toistolauseella toteutettuna seuraavalta: -```java + + +In practical terms, the for each loop described above hides some parts of the for loop we practised before. If implemented with a for loop, the for each repeat statement would look like this: + + + +```java +ArrayList teachers = new ArrayList<>(); + +teachers.add("Simon"); +teachers.add("Samuel"); +teachers.add("Ann"); +teachers.add("Anna"); +for (int i = 0; i < teachers.size(); i++) { + String teacher = teacher.get(i); + // contents of the for each loop: + System.out.println(teacher); +} ``` -Käytännössä for-each käy listan läpi yksi arvo kerrallaan. Lause määritellään muodossa `for (MuuttujanTyyppi muuttujanArvo: listanNimi)`, missä `MuuttujanTyyppi` on listalla olevien arvojen tyyppi ja `muuttujanArvo` on muuttuja, johon listan arvo asetetaan kunkin läpikäynnin yhteydessä. + + + +In practice the for each loop examines the values of the list in order one at a time. The expression is defined in the following format: `for (TypeOfVariable valueOfVariable: ) From d5af2962e26308d97d4f643bab218c0eb813cec0 Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Thu, 25 Jul 2019 12:51:09 +0300 Subject: [PATCH 5/6] Advanced to the end --- data/osa-3/2-listat.md | 581 +++++++++++++++++++++++++++++++++++------ 1 file changed, 507 insertions(+), 74 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index ca7679ac2..4e1a1b091 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -1686,19 +1686,28 @@ for (int i = 0; i < teachers.size(); i++) { -In practice the for each loop examines the values of the list in order one at a time. The expression is defined in the following format: `for (TypeOfVariable valueOfVariable: ) +In practice the for each loop examines the values of the list in order one at a time. The expression is defined in the following format: `for (TypeOfVariable nameOfVariable: nameOfList)`, where `TypeOfVariable` is the type of the values in the list, and `nameOfVariable` is the variable that is used to store each value in the list as we go through it. - +xxx + - -Ohjelmaan on toteutettu valmiina pohja, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Lisää ohjelmaan toiminnallisuus, joka lukujen lukemisen jälkeen laskee ja tulostaa listalla olevien lukujen summan. + - + + + +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + + +Modify the program so that after reading the numbers it calculates and prints the sum of the numbers in the list. + + + + + +**72** +**2** +**8** +**11** +**-1** + +Sum: 93 + - + -Toteuta ohjelma, joka lukee käyttäjältä lukuja listalle. Syötteiden lukeminen päätetään kun käyttäjä syöttää luvun -1. + -Kun lukujen lukeminen lopetetaan, laske listalla olevien lukujen keskiarvo ja tulosta se. - + + +The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1. + + + +When reading ends, calculate the average of the numbers in it, and then print that value. + + + + + +**72** +**2** +**8** +**11** +**-1** + +Average: 23.25 + -## Listalta poistaminen ja arvon olemassaolon tarkistaminen + +## Removing from list and checking the existence of a value -Listan metodi **remove** poistaa listalta parametrina annettuun indeksiin liittyvän arvon. Parametri annetaan kokonaislukuna. + -```java +The list method **remove** removes the value that is placed in the index that is given as the parameter. The parameter (index) in an integer. + + + + +```java +ArrayList list = new ArrayList<>(); + +list.add("First"); +list.add("Second"); +list.add("Third"); + +list.remove(1); + +System.out.println("Index 0 so the first value: " + list.get(0)); +System.out.println("Index 1 so the second value: " + list.get(1)); ``` - + + + + +First +Third + -Jos parametri on listan sisältämien arvojen tyyppinen, mutta ei kokonaisluku (kokonaislukua käytetään paikasta poistamiseen), voidaan sitä käyttää arvon poistamiseen listalta suoraan. + +If the parameter given to `remove` is the same type as the values in the list, excluding integers (which are used to remove based on placement), it can be used to remove the parameter value directly from the list. -```java + + + +```java +ArrayList list = new ArrayList<>(); + +list.add("First"); +list.add("Second"); +list.add("Third"); + +list.remove("First"); + +System.out.println("Index 0 so the first value: " + lista.get(0)); +System.out.println("Index 1 so the second value: " + lista.get(1)); ``` - + + + + +Second +Third + -Jos lista sisältää kokonaislukuja, ei listalta voi poistaa lukua antamalla remove-metodille luvun `int`-tyyppisenä parametrina. Tämä poistaisi luvun annetusta indeksistä. Kokonaislukutyyppisten arvojen poistaminen tapahtuu muuttamalla arvot Integer-tyyppisiksi, eli kapseloimalla ne Integer-tyyppisiksi (viittaustyyppisiksi), Integer-luokan metodilla `valueOf`. + +If the list contains integers, you cannot remove a number value by giving an `int` type parameter to the remove method. This would remove the number from the index that the parameter indicates, instead of an element on the list that has the same value as the parameter. To remove an integer type value you can convert the parameter to Integer type; this is achieved by the `valueOf` method of the Integer class. -```java +// jesper: should be ArrayList + + + + +```java +ArrayList list = new ArrayList<>(); + +list.add(15); +list.add(18); +list.add(21); +list.add(24); + +list.remove(2); +list.remove(Integer.valueOf(15)); + +System.out.println("Index 0 so the first value: " + list.get(0)); +System.out.println("Index 1 so the second value: " + list.get(1)); ``` @@ -1818,10 +1923,14 @@ System.out.println("Paikka 1 eli toinen: " + lista.get(1)); -Arvon hakeminen listalta onnistuu listan metodilla **contains**. Metodi saa haettavan arvon parametrina ja palauttaa boolean-tyyppisen arvon (`true` tai `false`), joka kertoo löytyykö haettua arvoa listalta. +// jesper: "arvon hakeminen listalta" - tuntuu vihjaavan enemmän gettiin (haetaan -> saadaan). arvon sisältymisen tarkastaminen? arvon olemassaolo listalla voidaan tarkastaa? + -```java +The list method **contains** can be used to check the existence of a value in the list. The method receives the value to be searched as its parameter, and it returns a boolean type value (`true` or `false`) that indicates whether that value is stored in the list. + + + + +```java +ArrayList list = new ArrayList<>(); + +list.add("First"); +list.add("Second"); +list.add("Third"); + +System.out.println("Can we find first? " + lista.contains("First")); + +boolean found = list.contains("Second"); +if (found) { + System.out.println("Second was found"); +} + +// or more simply +if (list.contains("Second")) { + System.out.println("Second can still be found"); +} ``` - + + + + +Can we find first? true +Second was found +Second can still be found + - + + -Tehtäväpohjassa on ohjelma, joka lukee käyttäjältä syötteitä. Lisää ohjelmaan toiminnallisuus, missä syötteiden lukemisen jälkeen kysytään vielä yhtä merkkijonoa. Ohjelma kertoo tämän jälkeen löytyikö käyttäjän syöttämä merkkijono listalta vai ei. - +// jesper: siis kysytäänkö aina neljä? vai lopettaako tyhjä merkkijono lukemisen? + + + +In the exercise template there is a program that reads inputs from the user. Add the following functionality to it: after reading the inputs one more string is requested from the user. The program then tell whether that string was found in the list or not. + + +**Tom** +**Emma** +**Alex** +**Mary** + +Who is searched for? **Mary** +Mary was found! + + + + + + + +**Tom** +**Emma** +**Alex** +**Mary** + +Who is searched for? **Logan** +Logan was not found! + -## Lista metodin parametrina + -Kuten muutkin muuttujat, myös listan voi asettaa metodin parametriksi. Kun lista määritellään metodin parametriksi, määritellään parametrin tyypiksi listan tyyppi sekä listan sisältämien arvojen tyyppi. Alla oleva metodi `tulosta` tulostaa listan arvot yksitellen. +## List as a method parameter -```java + + +Like other variables, a list, too, can be used as a parameter to a method. When the method is defined to take a list as a parameter, the type of the parameter is defined as the type of the list and the type of the values contained by that list. Below, the method `print` prints the values in the list one by one. + + + +```java +public static void print(ArrayList list) { + for (String value: list) { + System.out.println(value); + } +} ``` -Metodin kutsuminen on tuttua ja toimii samalla tavalla kuin edellisessä osassa toteuttamiemme metodien kohdalla. Alla olevassa esimerkissä käytetään edellä toteutettua metodia `tulosta`. + -```java +We are very familiar with methods, and it works indentically in this case. In the example below we use the `print` method that was implemented above. + + + +```java +ArrayList strings = new ArrayList<>(); + +strings.add("First"); +strings.add("Second"); +strings.add("Third"); + +print(strings); ``` - + + + + +First +Second +Third + + -Metodin määrittelyssä annettu parametrin nimi ei riipu metodikutsun yhteydessä metodille parametrina annettavasta listasta. Metodia `tulosta` kutsuvassa ohjelmassa listamuuttujan nimi on `merkkijonot`, mutta metodissa `tulosta` muuttujan nimi on `lista` -- tulostettavia arvoja sisältävää listaa kuvaavan muuttujan nimi voisi olla myös vaikkapa `tulostettavat`. +The chosen parameter in the method definition is not dependent on the list that is passed as parameter in the method call. In the program that calls `print` the name of the list variable is `string`, but inside the method `print` the variable is called `list` -- the name of the variable that stores the list could also be `printables`, for example. -Metodille voidaan määritellä myös useampia muuttujia. Alla olevassa esimerkissä tulostetaan kaikki ne parametrina annetussa listassa olevat luvut, jotka ovat pienempiä kuin toisena parametrina annettu luku. + +It's also possible to define multiple variables for a method. In the example the method receives two parameters: a list of numbers and a threshold value. It then prints all the numbers in the list that are smaller than the second parameter. -```java + + ```java +public static void printSmallerThan(ArrayList numbers, int threshold) { + for (int number: numbers) { + if (number < threshold) { + System.out.println(number); + } + } +} +``` + + + +```java +ArrayList list = new ArrayList<>(); + +list.add(1); +list.add(2); +list.add(3); +list.add(2); +list.add(1); + +printSmallerThan(list, 3); ``` @@ -1952,11 +2176,17 @@ tulostaPienemmat(lista, 3); - + -Luo tehtäväpohjaan metodi `public static void tulostaRajatutLuvut(ArrayList luvut, int alaraja, int ylaraja)`. Metodin tulee tulostaa parametrina annetulta listalta ne luvut, joiden arvot ovat välillä [alaraja, ylaraja]. Alla on muutama esimerkki metodin toiminnasta. + -```java + + + + +Create the method `public static void printNumbersInRange(ArrayList numbers, int lowerLimit, int upperLimit)` in the exercise template. The method prints the numbers in the given list whose values are in the range [lowerLimit, upperLimit]. A few examples of using the method are supplied below. + + + +```java +ArrayList numbers = new ArrayList<>(); +numbers.add(3); +numbers.add(2); +numbers.add(6); +numbers.add(-1); +numbers.add(5); +numnbers.add(1); + +System.out.println("The numbers in the range [0, 5]"); +printNumbersInRange(numbers, 0, 5); + +System.out.println("The numbers in the range [3, 10]"); +printNumbersInRange(numbers, 3, 10); ``` - + + + + +The numbers in the range [0, 5] +3 +2 +5 +1 +The numbers in the range [3, 10] +3 +6 +5 + -Kuten aiemmin, metodi voi myös palauttaa arvon. Arvon palauttavilla metodeilla on `void`-määreen sijaan palautettavan arvon tyyppi, jonka lisäksi arvon palauttaminen tapahtuu `return`-komennolla. Alla oleva metodi palauttaa listan koon. + +As was the case before, a method can also return a value. The methods that return values have the type of the return value in place of the `void` keyword, and the actual returning of the value is done by the `return` command. The method below returns the size of the list. -```java + + + +```java +public static int size(ArrayList list) { + return list.size(); +} ``` -Metodeihin voi myös määritellä omia muuttujia. Alla oleva metodi laskee listalla olevien lukujen keskiarvon. Mikäli lista on tyhjä, metodi palauttaa luvun -1. + -```java +You can also define own variables for methods. The method below calculates the average of the numbers in the list. If the list is empty, it returns the number -1. + + + +```java +public static double average(ArrayList numbers) { + if (numbers.size() == 0) { + return -1.0; + } + + int sum = 0; + for (int number: numbers) { + sum = sum + number; + } + + return 1.0 * sum / numbers.size(); +} ``` + - + -Luo tehtäväpohjaan metodi `public static int summa(ArrayList luvut)`. Metodin tulee palauttaa parametrina annetun listan lukujen summa. -```java + + +Create the method `public static int sum(ArrayList numers)` in the exercise template. The method is to return the sum of the numbers in the parameter list. + + + +```java +ArrayList numbers = new ArrayList<>(); +numbers.add(3); +numbers.add(2); +numbers.add(6); +numbers.add(-1); +System.out.println(sum(numbers)); + +numbers.add(5); +numbers.add(1); +System.out.println(sum(numbers)); ``` @@ -2043,17 +2345,28 @@ System.out.println(summa(luvut)); -## Listan kopioitumisesta metodin parametriksi + -Olemme aiemmin käyttäneet kokonaislukuja, liukulukuja ym. metodin parametrina. Kun muuttujia kuten `int` käytetään metodin parametrina, kopioituu muuttujan arvo metodin käyttöön. Täsmälleen sama asia tapahtuu myös listan tapauksessa. +## On copying the list to a method parameter -Listat ja oikeastaan lähes kaikki muuttujat, joihin voi lisätä paljon tietoa, ovat _viittaustyyppisiä muuttujia_. Tämä tarkoittaa sitä, että muuttujan arvo on viite, joka osoittaa tiedon sisältämään paikkaan. -Kun lista tai oikeastaan mikä viittaustyyppinen muuttuja kopioidaan metodin käyttöön, kopioituu metodin käyttöön muuttujan arvo eli _viite_. Tällöin **metodin käyttöön tulee viite viittaustyyppisen muuttujan todelliseen arvoon**, ja metodissa voi muokata alkuperäistä viittaustyyppistä arvoa kuten listaa. Käytännössä siis metodin parametrina saatu lista on sama kuin mitä metodia kutsuvassa ohjelmassa käytetään. + -Tarkastellaan tätä lyhyesti seuraavan metodin kautta. +Earlier we have used integers, floating point numbers, etc. parameters for method. When variables such as `int` are used as method parameters, the value of the variable is copied for the method's use. Exactly the same occurs in the case that the parameter is a list. -```java + + +Lists, among practically all the variables that can store large amounts of information, are _reference type variables_. This means that the value of the variable is a reference that points to the location that contains the information. + + + +When a list (or any reference type variable) is copied for the method to use, the method receives the value of the list variable, i.e. a _reference_. In such a case the **method receives a reference to the real value of a reference type variable**, and the method is able to modify the value of the original reference type variable, such as a list. In practice: the list that the method receives as a parameter is the same list that is used in the program that calls the mehtod. + + + +Let's briefly examine this phenomenon with the following method. + + ```java +public static void removeFirst(ArrayList numbers) { + if (numbers.size() == 0) { + return; + } + + numbers.remove(0); +} +``` + + + +```java +ArrayList numbers = new ArrayList<>(); +numbers.add(3); +numbers.add(2); +numbers.add(6); +numbers.add(-1); + +System.out.println(numbers); + +removeFirst(numbers); + +System.out.println(numbers); + +removeFirst(numbers); +removeFirst(numbers); +removeFirst(numbers); + +System.out.println(numbers); ``` @@ -2091,11 +2433,16 @@ System.out.println(luvut); - + -Luo tehtäväpohjaan metodi `public static void poistaViimeinen(ArrayList mjonot)`. Metodin tulee poistaa parametrina saadusta listasta viimeisin arvo. Mikäli lista on tyhjä, metodin ei tule tehdä mitään. + -```java + + + +Create the method `public static void removeLast(ArrayList strings)` in the exercise template. The method should remove the last value in the list it receives as a parameter. If the list is empty, the method does nothing. + + + +```java +ArrayList strings = new ArrayList<>(); + +strings.add("First"); +strings.add("Second"); +strings.add("Third"); + +System.out.println(strings); + +removeLast(strings); +removeLast(strings); + +System.out.println(strings); ``` - + + + +[First, Second, Third] +[First] -## Yhteenveto listan metodeista + -ArrayListillä on useita hyödyllisiä metodeja. Metodin toiminnallisuus suoritetaan aina sille listaoliolle, mihin liittyen metodia kutsutaan -- yhteys määritellään pisteellä. Alla oleva esimerkki näyttää, että listoja -- kuten muitakin muuttujia -- voi olla ohjelmassa useampia. Alla luodaan kaksi erillistä listaa, joita käsitellään. +## Summarizing the list methods -```java + + +ArrayList contains a great many useful methods. The method always operates on the list object that is connected to the method call -- the connection is established with a dot. The example below showcases that a program can contain multiple lists -- which holds true for other variables as well. Two separate lists are created below. + + + +

Tehtävien nimet käännettävä

+ +```java +ArrayList exercises1 = new ArrayList<>(); +ArrayList exercises2 = new ArrayList<>(); + +exercises1.add("Ada Lovelace"); +exercises1.add("Hello World! (Ja Mualima!)"); +exercises1.add("Kuusi"); + +tehtavat2.add("Adding a positive number"); +tehtavat2.add("Työntekijän eläkevakuutus"); + +System.out.println("The size of list 1: " + exercises1.size()); +System.out.println("The size of list 2: " + exercises2.size()); + +System.out.println("The first value of the first list " + exercises1.get(0)); +System.out.println("The last value of the second list " + exercises2.get(exercises2.size() - 1)); ``` - + + + + +The size of list 1: 3 +The size of list 2: 2 +The first value of the first list Ada Lovelace +The last value of the second list Työntekijän eläkevakuutus + -Jokainen lista on oma erillinen kokonaisuutensa ja listan metodit käsittelevät aina sitä listaa, mille metodia kutsutaan. Alla on yhteenveto listan metodeista. Yhteenvedossa oletetaan, että luotava lista sisältää merkkijonotyyppisiä muuttujia. + -* Listalle lisääminen tapahtuu metodilla `add`, jolle annetaan parametrina lisättävä arvo. -```java +Each list is its own separate entity, and the listmethods always target the list that is used to call the method. Below is a summary of some list methods. It is assumed that created lists contains string type variables. + + +* Adding to a list is done with the method `add` that receives the value to be added as a parameter. + ```java +ArrayList list = new ArrayList<>(); +list.add("hello world!"); +``` + +* The number of elements in a list can be discovered with the non-parameterized method `size`; it returns an integer. + ```java +ArrayList list = new ArrayList<>(); +int size = list.size(); +System.out.println(size); +``` + +* You can retrieve a value from a certain index with the method `get` that is given the wanted index as a parameter. + ```java +ArrayList list = new ArrayList<>(); +list.add("hello world!"); +String string = list.get(0); +System.out.println(string); +``` + +* Removing from a list is done with the help of `remove`. It receives as a parameter one of the following two: the value that is to be removed, or the index of the value to be removed. + ```java +ArrayList list = new ArrayList<>(); +// remove the string "hello world!" +list.remove("hello world!"); + // remove the value at index 3 +list.remove(3); +``` + +* Testing the existence of a value is done with the method `contains`. It is given the value to be searched for as a parameter, and it returns a boolean. + +```java +ArrayList list = new ArrayList<>(); +boolean found = list.contains("hello world!"); ``` From 1ad53adb74f618fb93faed257bf7d6c3ad989947 Mon Sep 17 00:00:00 2001 From: Jesper Kuutti Date: Thu, 25 Jul 2019 13:13:02 +0300 Subject: [PATCH 6/6] Fixed uncertain parts --- data/osa-3/2-listat.md | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/data/osa-3/2-listat.md b/data/osa-3/2-listat.md index 4e1a1b091..1873c3a82 100644 --- a/data/osa-3/2-listat.md +++ b/data/osa-3/2-listat.md @@ -1876,8 +1876,6 @@ Third If the list contains integers, you cannot remove a number value by giving an `int` type parameter to the remove method. This would remove the number from the index that the parameter indicates, instead of an element on the list that has the same value as the parameter. To remove an integer type value you can convert the parameter to Integer type; this is achieved by the `valueOf` method of the Integer class. -// jesper: should be ArrayList - ```java -ArrayList list = new ArrayList<>(); +ArrayList list = new ArrayList<>(); list.add(15); list.add(18); @@ -1923,8 +1921,6 @@ System.out.println("Index 1 so the second value: " + list.get(1)); -// jesper: "arvon hakeminen listalta" - tuntuu vihjaavan enemmän gettiin (haetaan -> saadaan). arvon sisältymisen tarkastaminen? arvon olemassaolo listalla voidaan tarkastaa? - The list method **contains** can be used to check the existence of a value in the list. The method receives the value to be searched as its parameter, and it returns a boolean type value (`true` or `false`) that indicates whether that value is stored in the list. @@ -1992,11 +1988,10 @@ Second can still be found -// jesper: siis kysytäänkö aina neljä? vai lopettaako tyhjä merkkijono lukemisen? -In the exercise template there is a program that reads inputs from the user. Add the following functionality to it: after reading the inputs one more string is requested from the user. The program then tell whether that string was found in the list or not. +In the exercise template there is a program that reads inputs from the user until an empty string is entered. Add the following functionality to it: after reading the inputs one more string is requested from the user. The program then tell whether that string was found in the list or not. -

Tehtävien nimet käännettävä

+ + ```java ArrayList exercises1 = new ArrayList<>();