Udfordring: Visning af Papegøjeinformation
Opgave
Swipe to start coding
Din opgave er at skrive en toString()
-metode, der viser alle oplysninger om papegøjen.
- Brug return-nøgleordet i
toString()
-metoden til at angive metodens output. - Start med at oprette en streng, enten ved sammenkædning eller strengformatering, begyndende med noget som
Parrot{
. - Tilføj hvert felt til strengen ved at bruge
+
til sammenkædning, og inkluder både feltnavn og dets værdi (f.eks."name='" + name + "'"
). - Adskil hvert felt med et komma og et mellemrum for bedre læsbarhed.
- Afslut strengen med en afsluttende krølleparentes
}
for korrekt at repræsentere objektet. - Returnér til sidst den formaterede streng fra
toString()
-metoden.
Løsning
solution.java
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
class Parrot {
String name;
int age;
String color;
boolean canParrotTalk;
@Override
public String toString() {
return "Parrot{" +
"name='" + name + "'" +
", age=" + age +
", color='" + color + "'" +
", canParrotTalk=" + canParrotTalk +
'}';
}
public Parrot(String name, int age, String color, boolean canParrotTalk) {
this.name = name;
this.age = age;
this.color = color;
this.canParrotTalk = canParrotTalk;
}
}
public class Main {
public static void main(String[] args) {
Parrot bubba = new Parrot("Bubba", 1, "Yellow", true);
Parrot rio = new Parrot("Rio", 3, "Blue", false);
Parrot ollie = new Parrot("Ollie", 2, "Red", true);
System.out.println(bubba);
System.out.println(rio);
System.out.println(ollie);
}
}
Var alt klart?
Tak for dine kommentarer!
Sektion 4. Kapitel 9
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.example;
class Parrot {
String name;
int age;
String color;
boolean canParrotTalk;
@Override
public String toString() {
return ___;
}
public Parrot(String name, int age, String color, boolean canParrotTalk) {
this.name = name;
this.age = age;
this.color = color;
this.canParrotTalk = canParrotTalk;
}
}
public class Main {
public static void main(String[] args) {
Parrot bubba = new Parrot("Bubba", 1, "Yellow", true);
Parrot rio = new Parrot("Rio", 3, "Blue", false);
Parrot ollie = new Parrot("Ollie", 2, "Red", true);
System.out.println(bubba);
System.out.println(rio);
System.out.println(ollie);
}
}
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat