forked from ZCW-Summer25/JavaFundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic.jsh
More file actions
585 lines (478 loc) · 16 KB
/
Copy pathtopic.jsh
File metadata and controls
585 lines (478 loc) · 16 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Instance Methods Practice - Complete the method implementations
import java.util.ArrayList;
// Exercise 1: Calculator with instance methods
class Calculator {
double result;
public Calculator() {
result = 0.0;
}
public void add(double value) {
result += value;
}
public void subtract(double value) {
result -= value;
}
public void multiply(double value) {
result *= value;
}
public void divide(double value) {
if (value == 0) {
System.out.println("Can't divide by 0");
return;
}
result /= value;
}
public double getResult() {
return result;
}
public void clear() {
result = 0.0;
}
}
// Exercise 2: Text processing with instance methods
class TextProcessor {
String text;
public TextProcessor(String initialText) {
this.text = initialText;
}
public void setText(String newText) {
text = newText;
}
public String getText() {
return text;
}
public int getLength() {
return text.length();
}
public String toUpperCase() {
return text.toUpperCase();
}
public String toLowerCase() {
return text.toLowerCase();
}
public String reverse() {
return new StringBuilder(text).reverse().toString();
}
public boolean contains(String substring) {
if (text.contains(substring)) {
return true;
}
return false;
}
public int getWordCount() {
if (text == null || text.trim().isEmpty()) return 0;
return text.trim().split("\\s+").length;
}
}
// Exercise 3: Counter with state management
class Counter {
int count;
int step;
public Counter(int initialCount, int stepValue) {
this.count = initialCount;
this.step = stepValue;
}
public void increment() {
count += step;
}
public void decrement() {
count -= step;
}
public void reset() {
count = 0;
}
public int getCount() {
return count;
}
public void setStep(int newStep) {
step = newStep;
}
public int getStep() {
return step;
}
public boolean isPositive() {
if (count > 0) {
return true;
}
return false;
}
public boolean isNegative() {
if (count < 0) {
return true;
}
return false;
}
}
// Exercise 4: Temperature conversion and validation
class Temperature {
double celsius;
public Temperature(double temp, String unit) {
if (unit.equalsIgnoreCase("C")) {
celsius = temp;
} else if (unit.equalsIgnoreCase("F")) {
celsius = (temp - 32) * 5.0 / 9.0;
} else if (unit.equalsIgnoreCase("K")) {
celsius = temp - 273.15;
} else {
celsius = 0.0;
}
}
public double getCelsius() {
return celsius;
}
public double getFahrenheit() {
return celsius * 9.0 / 5.0 + 32.0;
}
public double getKelvin() {
return celsius + 273.15;
}
public void setCelsius(double temp) {
celsius = temp;
}
public void setFahrenheit(double temp) {
celsius = (temp - 32) * 5.0 / 9.0;
}
public void setKelvin(double temp) {
celsius = temp - 273.15;
}
public boolean isFreezingWater() {
if (celsius <= 0.0) {
return true;
}
return false;
}
public boolean isBoilingWater() {
if (celsius >= 100.0) {
return true;
}
return false;
}
public String getTemperatureCategory() {
if (celsius <= 0.0) {
return "Cold";
} else if (celsius > 0 && celsius <= 20) {
return "Mild";
} else if (celsius > 20 && celsius < 35) {
return "Hot";
} else if (celsius >= 35) {
return "Extreme";
} else {
return "";
}
}
}
// Exercise 5: Shopping cart with item management
class ShoppingCart {
ArrayList<String> items;
ArrayList<Double> prices;
public ShoppingCart() {
items = new ArrayList<>();
prices = new ArrayList<>();
}
public void addItem(String item, double price) {
items.add(item);
prices.add(price);
}
public void removeItem(String item) {
int index = items.indexOf(item);
if (index != -1) {
items.remove(index);
prices.remove(index);
}
}
public int getItemCount() {
return items.size();
}
public double calculateTotal() {
double sum =0.0;
for (double price : prices) {
sum += price;
}
return sum;
}
public double calculateAverage() {
return prices.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
}
public String getMostExpensive() {
if (items.isEmpty()) return "";
double maxPrice = prices.get(0);
int maxIndex = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices.get(i) > maxPrice) {
maxPrice = prices.get(i);
maxIndex = i;
}
}
return items.get(maxIndex);
}
public String getCheapest() {
if (items.isEmpty()) return "";
double minPrice = prices.get(0);
int minIndex = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices.get(i) < minPrice) {
minPrice = prices.get(i);
minIndex = i;
}
}
return items.get(minIndex);
}
public boolean containsItem(String item) {
return items.contains(item);
}
public void clear() {
items.clear();
prices.clear();
}
}
// Exercise 6: Bank account with transaction management
class BankAccount {
String accountNumber;
double balance;
ArrayList<String> transactionHistory;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
this.transactionHistory = new ArrayList<>();
}
public boolean deposit(double amount) {
if (amount > 0) {
balance += amount;
transactionHistory.add(String.format("Deposited $%.2f", amount));
return true;
}
return false;
}
public boolean withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
transactionHistory.add(String.format("Withdrawal $%.2f", amount));
return true;
}
transactionHistory.add(String.format("Withdrawal Failed $%.2f", amount));
return false;
}
public boolean transfer(BankAccount toAccount, double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
transactionHistory.add(String.format("Transferred $%.2f to %s", amount, toAccount.accountNumber));
toAccount.balance += amount;
toAccount.transactionHistory.add(String.format("Received $%.2f from %s", amount, this.accountNumber));
return true;
} else {
transactionHistory.add(String.format("Transfer Failed $%.2f to %s", amount, toAccount.accountNumber));
return false;
}
}
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
public ArrayList<String> getTransactionHistory() {
return transactionHistory;
}
public int getTransactionCount() {
return transactionHistory.size();
}
public boolean hasInsufficientFunds(double amount) {
return balance < amount;
}
public double calculateInterest(double rate) {
return balance * rate;
}
}
// Exercise 7: Student grade book
class StudentGradeBook {
String studentName;
ArrayList<Double> grades;
public StudentGradeBook(String name) {
this.studentName = name;
grades = new ArrayList<>();
}
public boolean addGrade(double grade) {
// TODO: Add grade (validate 0-100 range)
// Return true if valid and added
if (grade >= 0 && grade <= 100) {
grades.add(grade);
return true;
}
return false;
}
public boolean removeLowestGrade() {
if (grades.isEmpty()) return false;
double min = grades.get(0);
int minIndex = 0;
for (int i = 1; i < grades.size(); i++) {
if (grades.get(i) < min) {
min = grades.get(i);
minIndex = i;
}
}
grades.remove(minIndex);
return true;
}
public int getGradeCount() {
return grades.size();
}
public double calculateAverage() {
if (grades.isEmpty()) return 0.0;
double sum = 0.0;
for (double grade : grades) {
sum += grade;
}
return sum / grades.size();
}
public double getHighestGrade() {
if (grades.isEmpty()) return 0.0;
double max = grades.get(0);
for (double grade : grades) {
if (grade > max) {
max = grade;
}
}
return max;
}
public double getLowestGrade() {
if (grades.isEmpty()) return 0.0;
double min = grades.get(0);
for (double grade : grades) {
if (grade < min) {
min = grade;
}
}
return min;
}
public String getLetterGrade() {
double avg = calculateAverage();
if (avg >= 90 && avg <= 100) {
return "A";
} else if (avg >= 80) {
return "B";
} else if (avg >= 70) {
return "C";
} else if (avg >= 60) {
return "D";
} else {
return "F";
}
}
public boolean isPassingGrade() {
return calculateAverage() >= 60.0;
}
public String getGradesSummary() {
int count = getGradeCount();
double avg = calculateAverage();
String letter = getLetterGrade();
return String.format("Student: %s, Grades: %d, Average: %.2f, Letter: %s.", studentName, count, avg, letter);
}
public boolean hasGradeAbove(double threshold) {
for (double grade : grades) {
if (grade > threshold) {
return true;
}
}
return false;
}
}
// Test your implementations below:
// Test Calculator
System.out.println("=== Testing Calculator ===");
Calculator calc = new Calculator();
System.out.println("Initial result: " + calc.getResult()); // Should be 0.0
calc.add(10);
System.out.println("After adding 10: " + calc.getResult()); // Should be 10.0
calc.multiply(2);
System.out.println("After multiplying by 2: " + calc.getResult()); // Should be 20.0
calc.subtract(5);
System.out.println("After subtracting 5: " + calc.getResult()); // Should be 15.0
calc.divide(3);
System.out.println("After dividing by 3: " + calc.getResult()); // Should be 5.0
calc.clear();
System.out.println("After clear: " + calc.getResult()); // Should be 0.0
// Test TextProcessor
System.out.println("\n=== Testing TextProcessor ===");
TextProcessor processor = new TextProcessor("Hello World");
System.out.println("Original text: " + processor.getText()); // "Hello World"
System.out.println("Length: " + processor.getLength()); // 11
System.out.println("Uppercase: " + processor.toUpperCase()); // "HELLO WORLD"
System.out.println("Lowercase: " + processor.toLowerCase()); // "hello world"
System.out.println("Reversed: " + processor.reverse()); // "dlroW olleH"
System.out.println("Contains 'World': " + processor.contains("World")); // true
System.out.println("Word count: " + processor.getWordCount()); // 2
// Test Counter
System.out.println("\n=== Testing Counter ===");
Counter counter = new Counter(5, 2);
System.out.println("Initial count: " + counter.getCount()); // 5
System.out.println("Step: " + counter.getStep()); // 2
System.out.println("Is positive: " + counter.isPositive()); // true
counter.increment();
System.out.println("After increment: " + counter.getCount()); // 7
counter.decrement();
counter.decrement();
counter.decrement();
counter.decrement();
System.out.println("After decrements: " + counter.getCount()); // -1
System.out.println("Is negative: " + counter.isNegative()); // true
counter.reset();
System.out.println("After reset: " + counter.getCount()); // 0
// Test Temperature
System.out.println("\n=== Testing Temperature ===");
Temperature temp = new Temperature(32, "F");
System.out.println("32°F in Celsius: " + temp.getCelsius()); // 0.0
System.out.println("In Kelvin: " + temp.getKelvin()); // 273.15
System.out.println("Is freezing water: " + temp.isFreezingWater()); // true
System.out.println("Category: " + temp.getTemperatureCategory()); // "Mild"
temp.setCelsius(25);
System.out.println("After setting to 25°C: " + temp.getFahrenheit()); // 77.0
System.out.println("Is boiling water: " + temp.isBoilingWater()); // false
// Test ShoppingCart
System.out.println("\n=== Testing ShoppingCart ===");
ShoppingCart cart = new ShoppingCart();
cart.addItem("Apple", 1.50);
cart.addItem("Banana", 0.75);
cart.addItem("Orange", 2.00);
System.out.println("Item count: " + cart.getItemCount()); // 3
System.out.println("Total: $" + cart.calculateTotal()); // 4.25
System.out.println("Average: $" + cart.calculateAverage()); // 1.42 (approximately)
System.out.println("Most expensive: " + cart.getMostExpensive()); // "Orange"
System.out.println("Cheapest: " + cart.getCheapest()); // "Banana"
System.out.println("Contains Apple: " + cart.containsItem("Apple")); // true
cart.removeItem("Banana");
System.out.println("After removing Banana, count: " + cart.getItemCount()); // 2
// Test BankAccount
System.out.println("\n=== Testing BankAccount ===");
BankAccount account1 = new BankAccount("123-456");
BankAccount account2 = new BankAccount("789-012");
System.out.println("Account 1 number: " + account1.getAccountNumber()); // "123-456"
System.out.println("Initial balance: $" + account1.getBalance()); // 0.0
account1.deposit(100.0);
System.out.println("After deposit: $" + account1.getBalance()); // 100.0
boolean withdrawn = account1.withdraw(30.0);
System.out.println("Withdrawal successful: " + withdrawn); // true
System.out.println("Balance after withdrawal: $" + account1.getBalance()); // 70.0
boolean transferred = account1.transfer(account2, 20.0);
System.out.println("Transfer successful: " + transferred); // true
System.out.println("Account 1 balance: $" + account1.getBalance()); // 50.0
System.out.println("Account 2 balance: $" + account2.getBalance()); // 20.0
System.out.println("Transaction count: " + account1.getTransactionCount()); // 3
System.out.println("Interest on $50 at 5%: $" + account1.calculateInterest(0.05)); // 2.5
// Test StudentGradeBook
System.out.println("\n=== Testing StudentGradeBook ===");
StudentGradeBook gradebook = new StudentGradeBook("Alice Johnson");
gradebook.addGrade(85.0);
gradebook.addGrade(92.0);
gradebook.addGrade(78.0);
gradebook.addGrade(96.0);
System.out.println("Grade count: " + gradebook.getGradeCount()); // 4
System.out.println("Average: " + gradebook.calculateAverage()); // 87.75
System.out.println("Highest: " + gradebook.getHighestGrade()); // 96.0
System.out.println("Lowest: " + gradebook.getLowestGrade()); // 78.0
System.out.println("Letter grade: " + gradebook.getLetterGrade()); // "B"
System.out.println("Is passing: " + gradebook.isPassingGrade()); // true
System.out.println("Has grade above 90: " + gradebook.hasGradeAbove(90.0)); // true
System.out.println("Summary: " + gradebook.getGradesSummary());
gradebook.removeLowestGrade();
System.out.println("After removing lowest, average: " + gradebook.calculateAverage()); // 91.0
System.out.println("\n=== All Tests Complete! ===");