Skip to content
Snippets Groups Projects
Commit 25c817aa authored by tornhale's avatar tornhale
Browse files

Kirjat-luokan poista-aliohjelmasta tehty parempi

parent d110e8f6
No related branches found
No related tags found
No related merge requests found
......@@ -37,6 +37,7 @@ import java.util.NoSuchElementException;
*
* int k2Id = k2.getId();
* kirjat.poista(k2Id);
* kirjat.poista(0); #THROWS NoSuchElementException
* kirjat.hae(k2Id); #THROWS NoSuchElementException
*
* </pre>
......@@ -81,17 +82,14 @@ public class Kirjat {
* @throws NoSuchElementException Jos id:tä vastaavaa kirjaa ei löydy
*/
public void poista(int id) throws NoSuchElementException {
for (int i = 0; i < alkiot.length; i++) {
if (alkiot[i].getId() == id) {
for (int j = i; j < alkiot.length - 1; j++) {
alkiot[j] = alkiot[j + 1];
}
alkiot[alkiot.length - 1] = null;
this.lkm--;
return;
int luku, kirj;
for (luku = 0, kirj = 0; luku < this.lkm; luku++) {
if (this.alkiot[luku].getId() != id) {
this.alkiot[kirj++] = this.alkiot[luku];
}
}
throw new NoSuchElementException("Kirjaa id:llä " + id + " ei löydy.");
this.lkm = kirj;
if (luku == kirj) throw new NoSuchElementException("Kirjaa id:llä " + id + " ei löydy.");
}
/**
......
......@@ -8,7 +8,7 @@ import Kirjalista.*;
/**
* Test class made by ComTest
* @version 2025.03.13 19:42:50 // Generated by ComTest
* @version 2025.03.17 16:07:43 // Generated by ComTest
*
*/
@SuppressWarnings({ "all" })
......@@ -47,30 +47,34 @@ public class KirjatTest {
int k2Id = k2.getId();
kirjat.poista(k2Id);
try {
kirjat.hae(k2Id);
kirjat.poista(0);
fail("Kirjat: 40 Did not throw NoSuchElementException");
} catch(NoSuchElementException _e_){ _e_.getMessage(); }
try {
kirjat.hae(k2Id);
fail("Kirjat: 41 Did not throw NoSuchElementException");
} catch(NoSuchElementException _e_){ _e_.getMessage(); }
} // Generated by ComTest END
// Generated by ComTest BEGIN
/** testLisaa53 */
/** testLisaa54 */
@Test
public void testLisaa53() { // Kirjat: 53
public void testLisaa54() { // Kirjat: 54
Kirja kirja = new Kirja();
Kirjat kirjat = new Kirjat();
try {
for (int i = 0; i < 8; i++) {
kirjat.lisaa(kirja);
assertEquals("From: Kirjat line: 59", i + 1, kirjat.getLkm());
assertEquals("From: Kirjat line: 60", i + 1, kirjat.getLkm());
}
assertEquals("From: Kirjat line: 61", 8, kirjat.getLkm());
assertEquals("From: Kirjat line: 62", 8, kirjat.getLkm());
} catch (SailoException e) {
System.out.println("Comtest heittaa virheita, jos ei ole trycatchia");
}
try {
kirjat.lisaa(kirja);
fail("Kirjat: 65 Did not throw SailoException");
fail("Kirjat: 66 Did not throw SailoException");
} catch(SailoException _e_){ _e_.getMessage(); }
} // Generated by ComTest END
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment