KaiquanMah commited on
Commit
7b4a862
·
verified ·
1 Parent(s): 89c5012

ArrayList<String>

Browse files
Week 4: Writing classes/05. Define attributes 2 ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ In the program, the class Recipe is defined.
2
+
3
+ Define the following attributes for the class:
4
+ String type: dish
5
+ Integer types: cookingtime and portions
6
+ String-type list: ingredients
7
+
8
+
9
+
10
+
11
+
12
+ import java.util.Random;
13
+ import java.util.ArrayList;
14
+
15
+ public class Test{
16
+ public static void main(String[] args){
17
+ System.out.println("Testing forming objects...");
18
+
19
+ ArrayList<String> ai1 = new ArrayList<>();
20
+ ArrayList<String> ai2 = new ArrayList<>();
21
+
22
+ ai1.add("water");
23
+ ai1.add("salt");
24
+ ai1.add("oats");
25
+
26
+ ai2.add("tomatoes");
27
+ ai2.add("cucumber");
28
+ ai2.add("salad");
29
+
30
+ Recipe porridge = new Recipe("Porridge", 15, 2, ai1);
31
+ Recipe salad = new Recipe("Salad", 5, 1, ai2);
32
+
33
+ System.out.println(porridge);
34
+ System.out.println(salad);
35
+ }
36
+ }
37
+
38
+ class Recipe {
39
+
40
+ //ADD ATTRIBUTES
41
+ String dish;
42
+ int cookingtime;
43
+ int portions;
44
+ ArrayList<String> ingredients;
45
+
46
+
47
+
48
+
49
+ //CONSTRUCTOR
50
+
51
+ public Recipe(String d, int ct, int p, ArrayList<String> ing) {
52
+ this.dish = d;
53
+ this.cookingtime = ct;
54
+ this.portions = p;
55
+ this.ingredients = ing;
56
+ }
57
+
58
+ @Override
59
+ public String toString() {
60
+ return "Recipe [dish=" + dish + ", cooking time=" + cookingtime + ", portions=" + portions
61
+ + ", ingredients=" + ingredients + "]";
62
+ }
63
+ }
64
+
65
+
66
+
67
+
68
+
69
+ Testing forming objects...
70
+ Recipe [dish=Porridge, cooking time=15, portions=2, ingredients=[water, salt, oats]]
71
+ Recipe [dish=Salad, cooking time=5, portions=1, ingredients=[tomatoes, cucumber, salad]]
72
+