-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainMenu.java
More file actions
865 lines (703 loc) · 37.2 KB
/
Copy pathMainMenu.java
File metadata and controls
865 lines (703 loc) · 37.2 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
import Engineering.EngCalc;
import Engineering.EngineeringCalculatorHandler;
import Engineering.ReflectiveUtils;
import Financial.*;
import LinearAlgebra.LinearAlgebraHandler;
import Parser.*;
import Scientific.*;
import Statistics.StatisticsHandler;
import java.util.*;
public class MainMenu {
private static final Map<String, Double> variables = new HashMap<>();
private static Node userDefinedFunction = null;
private static String functionType = "";
private static final String RESET = "\u001B[0m";
private static final String RED = "\u001B[31m";
private static final String GREEN = "\u001B[32m";
private static final String CYAN = "\u001B[36m";
private static final String YELLOW = "\u001B[33m";
private static final String WHITE = "\u001B[37m";
private static final String PINK = "\u001B[38;5;205m";
private static final String CLEAR_SCREEN = "\033[H\033[2J";
public static final String BLUE = "\u001B[34m";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (running) {
clearScreen();
displayBanner("default"); // Show the default banner
displayMenu(); // Show options based on the Command enum
System.out.print("\n" + GREEN + "Enter a command: " + RESET);
String input = scanner.nextLine().trim().toLowerCase();
try {
Command command = Command.valueOf(input.toUpperCase());
switch (command) {
case MENU:
break; // Menu redisplays automatically
case CALCULATOR:
clearScreen(); // Clear screen before launching calculator
evaluateExpression(scanner);
break;
case DIFFERENTIATE:
clearScreen(); // Clear screen
differentiateExpression(scanner);
break;
case FUNCTION:
clearScreen(); // Clear screen
handleFunctions(scanner);
break;
case LINEAR_ALGEBRA:
clearScreen(); // Clear screen
new LinearAlgebraHandler(scanner).startLinearAlgebra();
break;
case FINANCIAL_CALC:
clearScreen(); // Clear screen
launchFinancialCalculator(scanner);
break;
case SIMUL_SOLVER:
clearScreen(); // Clear screen
SimulSolverHandler simulSolver = new SimulSolverHandler(scanner);
simulSolver.startSimulSolver();
break;
case ENG_CALC:
clearScreen(); // Clear screen
new EngineeringCalculatorHandler().startEngineeringCalculator(scanner);
break;
case STAT_CALC:
StatisticsHandler statisticsHandler = new StatisticsHandler(scanner);
statisticsHandler.startStatisticsHandler();
break;
case SCI_CALC:
ScientificCalcHandler SciCalc = new ScientificCalcHandler();
SciCalc.startScientificCalculator(scanner);
break;
case EXIT:
System.out.println(GREEN + "Exiting the program. Goodbye!" + RESET);
running = false;
break;
default:
System.out.println(RED + "Unknown command. Type 'menu' to see options." + RESET);
}
} catch (IllegalArgumentException e) {
System.out.println(RED + "Invalid command. Type 'menu' to see options." + RESET);
}
}
}
private static void launchFinancialCalculator(Scanner scanner) {
clearScreen();
drawBanner("FINANCIAL CALCULATOR", CYAN); // Banner for FinancialCalc
System.out.println(YELLOW + "Launching Financial Calculator..." + RESET);
FinancialCalc financialCalc = new FinancialCalc();
financialCalc.startFinancialCalc(scanner); // Call the method inside FinancialCalc
pauseForUser(scanner); // Pause before returning to main menu
}
// Display Banner Method
private static void displayBanner(String mode) {
String banner = Banners.getBanner(mode);
System.out.println(CYAN + "+" + "-".repeat(50) + "+");
String[] lines = banner.split("\n");
for (String line : lines) {
int padding = 50 - stripAnsi(line).length();
System.out.println("| " + line + " ".repeat(padding - 1) + "|");
}
System.out.println("+" + "-".repeat(50) + "+" + RESET);
}
// Display Menu Based on Command Enum
private static void displayMenu() {
System.out.println(YELLOW + "\nAvailable Commands:\n" + RESET);
for (Command cmd : Command.values()) {
System.out.printf(GREEN + "- %-15s" + RESET + ": %s%n", cmd.name().toLowerCase(), cmd.getDescription());
}
}
// Clear Screen Method
private static void clearScreen() {
System.out.print(CLEAR_SCREEN);
System.out.flush();
}
// Utility Method to Strip ANSI for Alignment
private static String stripAnsi(String text) {
return text.replaceAll("\u001B\\[[;\\d]*m", "");
}
// Run Mode
private static void runMode(Scanner scanner, String mode) {
clearScreen();
displayBanner(mode);
System.out.println("\n" + CYAN + "Enter input for " + mode + " mode or type 'back' to return." + RESET);
while (true) {
System.out.print("\nInput field: ");
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("back")) break;
System.out.println("\n" + GREEN + "Processed input: " + input + RESET);
}
}
private static void simulateLoading(String message) {
System.out.print(YELLOW + message + RESET);
for (int i = 0; i < 3; i++) {
System.out.print(".");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Ignore
}
}
System.out.println();
}
private static void evaluateExpression(Scanner scanner) {
String lastResult = null; // To store the last result
while (true) {
clearScreen(); // Clear the screen before each input
displayBanner("calculator"); // Show the calculator banner
if (lastResult != null) {
// Display the last result at the top
System.out.println(GREEN + "Last Result: " + lastResult + RESET);
}
System.out.println("\n" + CYAN + "Calculator Mode: Enter mathematical expressions to evaluate." + RESET);
System.out.println(YELLOW + "Type 'menu' to return to the main menu." + RESET);
System.out.print("\nEnter expression: ");
String expression = scanner.nextLine().trim();
if (expression.equalsIgnoreCase("menu")) {
System.out.println(YELLOW + "Returning to the main menu..." + RESET);
return;
}
try {
Tokenizer tokenizer = new Tokenizer(expression);
Parser parser = new Parser(tokenizer);
Node ast = parser.parseExpression(0);
double result = ast.evaluate(variables);
lastResult = String.valueOf(result); // Save the result for display
} catch (Exception e) {
lastResult = RED + "Error: " + e.getMessage() + RESET; // Display the error
}
}
}
private static void differentiateExpression(Scanner scanner) {
String lastResult = null; // To store the last result
while (true) {
clearScreen(); // Clear the screen before each input
drawBanner("dy/dx", CYAN); // Show the differentiation banner
if (lastResult != null) {
// Display the last result at the top
System.out.println(GREEN + "Last Result: " + lastResult + RESET);
}
System.out.println("\n" + CYAN + "Differentiation Mode: Use the format 'dy/dx(function)'." + RESET);
System.out.println(YELLOW + "Type 'menu' to return to the main menu." + RESET);
System.out.print("\nEnter function: ");
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("menu")) {
System.out.println(YELLOW + "Returning to the main menu..." + RESET);
return;
}
if (!input.startsWith("dy/dx(") || !input.endsWith(")")) {
System.out.println(RED + "Invalid format. Use 'dy/dx(function)'." + RESET);
continue;
}
String functionPart = input.substring(6, input.length() - 1); // Extract the function inside parentheses
try {
Tokenizer tokenizer = new Tokenizer(functionPart);
Parser parser = new Parser(tokenizer);
Node function = parser.parseExpression(0);
Node derivative = function.differentiate("x");
lastResult = derivative.toString(); // Save the derivative for display
System.out.println(GREEN + "The derivative is: " + lastResult + RESET);
} catch (Exception e) {
lastResult = RED + "Error: " + e.getMessage() + RESET;
System.out.println(lastResult);
}
}
}
private static void handleFunctions(Scanner scanner) {
System.out.println("\nFunction Mode: Define a function and perform operations.");
System.out.println("Type 'menu' to return to the main menu.");
chooseFunctionType(scanner);
if (userDefinedFunction == null) {
System.out.println("No function defined. Returning to the main menu...");
return;
}
functionOperations(scanner);
}
private static void linearAlgebraMode(Scanner scanner) {
System.out.println("\nLinear Algebra Mode: Enter matrix or vector operations.");
System.out.println("Type 'menu' to return to the main menu.");
while (true) {
System.out.print("Enter operation: ");
String expression = scanner.nextLine().trim();
if (expression.equalsIgnoreCase("menu")) {
System.out.println("Returning to the main menu...");
return;
}
try {
// Extract function name and parameters
String functionName = expression.split("\\(")[0];
String params = expression.split("\\(")[1].replace(")", "");
// Parse parameters for linear algebra
Object[] arguments = parseParams(params);
EngCalc engCalc = new EngCalc();
Object result = ReflectiveUtils.invokeMethod(engCalc, functionName, arguments);
// Print the result
if (result instanceof double[][]) {
System.out.println(engCalc.matrixToString((double[][]) result));
} else {
System.out.println("Result: " + result);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
private static void drawBanner(String title, String color) {
int width = 50;
String padding = " ".repeat((width - title.length()) / 2);
System.out.println(color + "┌" + "─".repeat(width) + "┐" + RESET);
System.out.printf(color + "│%s%s%s│\n" + RESET, padding, title, padding);
System.out.println(color + "└" + "─".repeat(width) + "┘" + RESET);
}
private static void pauseForUser(Scanner scanner) {
System.out.print("\nPress Enter to continue...");
scanner.nextLine();
}
private static void functionOperations(Scanner scanner) {
while (true) {
clearScreen();
// Display Banner
displayBanner("function");
// Display Available Operations Table
System.out.println("\nAvailable Operations:");
System.out.println("┌────────────────────┬──────────────────────────────────────────┐");
System.out.printf("│ %-18s │ %-40s │\n", "Operation", "Description");
System.out.println("├────────────────────┼──────────────────────────────────────────┤");
System.out.printf("│ %-18s │ %-40s │\n", GREEN + "differentiate" + RESET, "Differentiate the defined function.");
System.out.printf("│ %-18s │ %-40s │\n", YELLOW + "find roots" + RESET, "Find roots of a single-variable function.");
System.out.printf("│ %-18s │ %-40s │\n", BLUE + "optimize" + RESET, "Optimize the function using methods.");
System.out.printf("│ %-18s │ %-40s │\n", RED + "menu" + RESET, "Return to the main menu.");
System.out.println("└────────────────────┴──────────────────────────────────────────┘");
// Prompt the user
System.out.print("\nEnter an operation: ");
String input = scanner.nextLine().trim().toLowerCase();
// Handle input
FunctionOperation operation = null;
try {
operation = FunctionOperation.valueOf(input.toUpperCase().replace(" ", "_"));
} catch (IllegalArgumentException e) {
System.out.println(RED + "Invalid operation. Please choose a valid option." + RESET);
pauseForUser(scanner);
continue;
}
switch (operation) {
case DIFFERENTIATE:
differentiateFunction(scanner);
pauseForUser(scanner);
break;
case FIND_ROOTS:
if (isSingleVariableFunction()) {
findRoots(scanner);
} else {
System.out.println(YELLOW + "Root-finding is only available for single-variable functions." + RESET);
}
pauseForUser(scanner);
break;
case OPTIMIZE:
optimizeFunction(scanner);
pauseForUser(scanner);
break;
case MENU:
System.out.println(GREEN + "\nReturning to the main menu..." + RESET);
pauseForUser(scanner);
return;
default:
System.out.println(RED + "Unknown operation. Please try again." + RESET);
}
}
}
public static Object[] parseParams(String params) {
try {
List<Object> paramList = new ArrayList<>();
EngCalc engCalc = new EngCalc();
int braceCount = 0;
StringBuilder currentParam = new StringBuilder();
for (char c : params.toCharArray()) {
if (c == '{') braceCount++;
else if (c == '}') braceCount--;
if (c == ',' && braceCount == 0) {
paramList.add(currentParam.toString().trim());
currentParam.setLength(0);
} else {
currentParam.append(c);
}
}
if (currentParam.length() > 0) {
paramList.add(currentParam.toString().trim());
}
Object[] arr = new Object[paramList.size()];
for (int i = 0; i < paramList.size(); i++) {
String param = paramList.get(i).toString();
// Integer detection
if (param.matches("\\d+")) {
arr[i] = Integer.parseInt(param);
}
// Matrix detection
else if (param.startsWith("{{") && param.endsWith("}}")) {
arr[i] = engCalc.matrix(param);
}
// Vector detection
else if (param.startsWith("{") && param.endsWith("}")) {
arr[i] = engCalc.vector(param); // Explicitly call vector method
}
// Default to double
else {
arr[i] = Double.parseDouble(param);
}
}
return arr;
} catch (NumberFormatException e) {
throw new NumberFormatException("Invalid number format");
} catch (Exception e) {
throw e;
}
}
private static boolean isSingleVariableFunction() {
if (userDefinedFunction == null) {
return false;
}
functionType = "single";
String functionString = userDefinedFunction.toString();
return functionString.contains("x") && !functionString.contains("y");
}
private static void chooseFunctionType(Scanner scanner) {
while (true) {
clearScreen();
drawBanner("FUNCTION TYPE SELECTION", CYAN);
// Display Choice Table
System.out.println("\nFunction Type Options:");
System.out.println("┌────────────────────┬──────────────────────────────────────────┐");
System.out.printf("│ %-18s │ %-40s │\n", "Choice", "Description");
System.out.println("├────────────────────┼──────────────────────────────────────────┤");
System.out.printf("│ %-18s │ %-40s │\n", GREEN + "1" + RESET, "Single-variable function (f(x))");
System.out.printf("│ %-18s │ %-40s │\n", YELLOW + "2" + RESET, "Multivariable function (f(x, y))");
System.out.printf("│ %-18s │ %-40s │\n", RED + "menu" + RESET, "Return to the main menu.");
System.out.println("└────────────────────┴──────────────────────────────────────────┘");
// Prompt for user input
System.out.print("\nEnter your choice: ");
String choice = scanner.nextLine().trim();
// Handle user input
if (choice.equalsIgnoreCase("menu")) {
System.out.println(GREEN + "Returning to the main menu..." + RESET);
pauseForUser(scanner);
return;
}
switch (choice) {
case "1":
System.out.println(YELLOW + "\nYou selected Single-variable function (f(x))." + RESET);
defineSingleVariableFunction(scanner);
return;
case "2":
System.out.println(YELLOW + "\nYou selected Multivariable function (f(x, y))." + RESET);
defineMultivariableFunction(scanner);
return;
default:
System.out.println(RED + "Invalid choice. Please enter '1', '2', or 'menu'." + RESET);
pauseForUser(scanner);
}
}
}
// Define a single-variable function
private static void defineSingleVariableFunction(Scanner scanner) {
clearScreen();
drawBanner("DEFINE SINGLE-VARIABLE FUNCTION", CYAN);
System.out.println("\n" + YELLOW + "Single-variable Function Definition" + RESET);
System.out.println("Define a function with variable 'x'. Example: x^2 + 2*x");
defineFunction(scanner, "x");
}
// Define a multivariable function
private static void defineMultivariableFunction(Scanner scanner) {
clearScreen();
drawBanner("DEFINE MULTIVARIABLE FUNCTION", CYAN);
System.out.println("\n" + YELLOW + "Multivariable Function Definition" + RESET);
System.out.println("Define a function with variables 'x' and 'y'. Example: x^2 + y^2 + 2*x*y");
functionType = "multi";
defineFunction(scanner, "x", "y");
}
// General function definition method with input validation
private static void defineFunction(Scanner scanner, String... variables) {
while (true) {
System.out.print("\nEnter function (or 'menu' to return): ");
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("menu")) {
System.out.println(GREEN + "\nReturning to the main menu..." + RESET);
pauseForUser(scanner);
return;
}
// Validate function input contains required variables
if (!validateFunctionInput(input, variables)) {
System.out.println(RED + "Error: Function must include variable(s) " + Arrays.toString(variables) + RESET);
continue;
}
try {
// Parse the function
Tokenizer tokenizer = new Tokenizer(input);
Parser parser = new Parser(tokenizer);
userDefinedFunction = parser.parseExpression(0);
// Success message
System.out.println(GREEN + "Function defined successfully as: " + RESET + userDefinedFunction);
pauseForUser(scanner);
functionOperations(scanner);
return;
} catch (Exception e) {
System.out.println(RED + "Error parsing function: " + e.getMessage() + RESET);
}
}
}
// Helper method to validate function input contains required variables
private static boolean validateFunctionInput(String input, String... variables) {
for (String variable : variables) {
if (!input.contains(variable)) {
return false;
}
}
return true;
}
private static boolean userDefinedFunctionContainsVariable(String variable) {
return userDefinedFunction.toString().contains(variable);
}
private static void differentiateFunction(Scanner scanner) {
if (userDefinedFunction == null) {
System.out.println("No function defined. Use 'functions' to define f(x) first.");
return;
}
try {
if ("single".equals(functionType)) {
// Single-variable case
Node derivative = userDefinedFunction.differentiate("x");
System.out.println("The derivative of f(x) is: " + derivative);
} else if ("multi".equals(functionType)) {
// Multivariable case: Differentiate with respect to x and y
Node partialX = userDefinedFunction.differentiate("x");
Node partialY = userDefinedFunction.differentiate("y");
// Display the gradient vector in a clean format
System.out.println("Gradient vector (Δf):");
System.out.println("Δf = | ∂f/∂x: " + partialX + " |");
System.out.println(" | ∂f/∂y: " + partialY + " |");
} else {
System.out.println("Unknown function type. Please define a function first.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
// Prompt for a double value
private static double promptForDouble(Scanner scanner, String message) {
while (true) {
System.out.print(message);
try {
return Double.parseDouble(scanner.nextLine().trim());
} catch (NumberFormatException e) {
System.out.println(RED + "Invalid input. Please enter a numeric value." + RESET);
}
}
}
// Prompt for an integer value
private static int promptForInt(Scanner scanner, String message) {
while (true) {
System.out.print(message);
try {
return Integer.parseInt(scanner.nextLine().trim());
} catch (NumberFormatException e) {
System.out.println(RED + "Invalid input. Please enter an integer value." + RESET);
}
}
}
private static void performNewtonMethod(Scanner scanner) {
clearScreen();
drawBanner("NEWTON'S METHOD", CYAN);
System.out.println(YELLOW + "\nRoot Finding with Newton's Method" + RESET);
System.out.println("Find roots of the function using an initial guess, tolerance, and max iterations.");
try {
double initialGuess = promptForDouble(scanner, "Enter initial guess: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double root = RootFinding.newtonsMethod(userDefinedFunction, "x", initialGuess, tolerance, maxIterations);
System.out.printf(GREEN + "\nRoot found using Newton's Method: x = %.6f\n" + RESET, root);
} catch (Exception e) {
System.out.println(RED + "Error: " + e.getMessage() + RESET);
}
pauseForUser(scanner);
}
private static void performSecantMethod(Scanner scanner) {
clearScreen();
drawBanner("SECANT METHOD", CYAN);
System.out.println(YELLOW + "\nRoot Finding with Secant Method" + RESET);
System.out.println("Find roots using two initial guesses, tolerance, and max iterations.");
try {
double x0 = promptForDouble(scanner, "Enter first guess: ");
double x1 = promptForDouble(scanner, "Enter second guess: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double root = RootFinding.secantMethod(userDefinedFunction, "x", x0, x1, tolerance, maxIterations);
System.out.printf(GREEN + "\nRoot found using Secant Method: x = %.6f\n" + RESET, root);
} catch (Exception e) {
System.out.println(RED + "Error: " + e.getMessage() + RESET);
}
pauseForUser(scanner);
}
private static void performBisectionMethod(Scanner scanner) {
clearScreen();
drawBanner("BISECTION METHOD", CYAN);
System.out.println(YELLOW + "\nRoot Finding with Bisection Method" + RESET);
System.out.println("Find roots using a lower and upper bound, tolerance, and max iterations.");
try {
double a = promptForDouble(scanner, "Enter lower bound (a): ");
double b = promptForDouble(scanner, "Enter upper bound (b): ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double fa = RootFinding.evaluateFunctionAtPoint(userDefinedFunction, "x", a);
double fb = RootFinding.evaluateFunctionAtPoint(userDefinedFunction, "x", b);
// Validate bounds
if (fa * fb > 0) {
System.out.println(RED + "Error: Function values at 'a' and 'b' must have opposite signs." + RESET);
System.out.printf("f(a) = %.6f, f(b) = %.6f\n", fa, fb);
return;
}
double root = RootFinding.bisectionMethod(userDefinedFunction, "x", a, b, tolerance, maxIterations);
System.out.printf(GREEN + "\nRoot found using Bisection Method: x = %.6f\n" + RESET, root);
} catch (Exception e) {
System.out.println(RED + "Error: " + e.getMessage() + RESET);
}
pauseForUser(scanner);
}
private static void findRoots(Scanner scanner) {
if (userDefinedFunction == null) {
System.out.println(RED + "No function defined. Use 'function' to define f(x) first." + RESET);
return;
}
while (true) {
clearScreen();
drawBanner("ROOT FINDING MODE", CYAN);
// Display available methods
System.out.println(YELLOW + "\nAvailable Root-Finding Methods:" + RESET);
System.out.println("┌──────────────┬──────────────────────────────────────┐");
System.out.printf("│ %-12s │ %-40s │\n", GREEN + "newton" + RESET, "Newton's Method for root finding.");
System.out.printf("│ %-12s │ %-40s │\n", BLUE + "secant" + RESET, "Secant Method for approximating roots.");
System.out.printf("│ %-12s │ %-40s │\n", YELLOW + "bisection" + RESET, "Bisection Method for interval-based roots.");
System.out.printf("│ %-12s │ %-40s │\n", RED + "menu" + RESET, "Return to the main menu.");
System.out.println("└──────────────┴──────────────────────────────────────┘");
// Prompt the user for a method
String method = promptInput(scanner, "Enter root-finding method: ").toLowerCase();
if (method.equals("menu")) {
System.out.println(YELLOW + "Returning to the main menu..." + RESET);
pauseForUser(scanner);
return;
}
try {
switch (method) {
case "newton":
performNewtonMethod(scanner);
break;
case "secant":
performSecantMethod(scanner);
break;
case "bisection":
performBisectionMethod(scanner);
break;
default:
System.out.println(RED + "Invalid option. Choose 'newton', 'secant', 'bisection', or 'menu'." + RESET);
}
} catch (NumberFormatException e) {
System.out.println(RED + "Invalid input. Please enter numeric values." + RESET);
} catch (Exception e) {
System.out.println(RED + "Error: " + e.getMessage() + RESET);
}
pauseForUser(scanner);
}
}
private static String promptInput(Scanner scanner, String message) {
while (true) {
System.out.print(CYAN + message + RESET);
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("menu")) {
return "menu"; // Global return for 'menu'
}
return input;
}
}
private static void optimizeFunction(Scanner scanner) {
if (userDefinedFunction == null) {
System.out.println(RED + "No function defined. Use 'function' to define f(x) or f(x, y) first." + RESET);
return;
}
while (true) {
clearScreen();
drawBanner("OPTIMIZATION MODE", CYAN);
// Display Available Methods
System.out.println(YELLOW + "\nChoose an optimization algorithm:" + RESET);
System.out.println(GREEN + "1. newtonian" + RESET + " : Use Newtonian optimization");
System.out.println(BLUE + "2. gradient" + RESET + " : Use Gradient Descent");
System.out.println(RED + "3. menu" + RESET + " : Return to the main menu");
// Prompt for input
System.out.print("\nEnter your choice: ");
String method = scanner.nextLine().trim().toLowerCase();
if (method.equals("menu")) {
System.out.println(YELLOW + "Returning to the main menu..." + RESET);
pauseForUser(scanner);
return;
}
try {
switch (method) {
case "newtonian":
handleNewtonianOptimization(scanner);
break;
case "gradient":
handleGradientDescent(scanner);
break;
default:
System.out.println(RED + "Invalid option. Please choose 'newtonian', 'gradient', or 'menu'." + RESET);
}
} catch (NumberFormatException e) {
System.out.println(RED + "Invalid input. Please enter numeric values only." + RESET);
} catch (Exception e) {
System.out.println(RED + "Error: " + e.getMessage() + RESET);
}
pauseForUser(scanner);
}
}
private static void handleNewtonianOptimization(Scanner scanner) throws Exception {
clearScreen();
drawBanner("NEWTONIAN OPTIMIZATION", BLUE);
if (userDefinedFunctionContainsVariable("y")) {
System.out.println(YELLOW + "\nMultivariable Newtonian Optimization" + RESET);
double x = promptForDouble(scanner, "Enter initial x value: ");
double y = promptForDouble(scanner, "Enter initial y value: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double[] result = Optimisation.newtonianOptimisationMultivariable(userDefinedFunction, x, y, tolerance, maxIterations);
System.out.printf(GREEN + "Optimal point: (x=%.6f, y=%.6f)%n" + RESET, result[0], result[1]);
} else {
System.out.println(YELLOW + "\nSingle-variable Newtonian Optimization" + RESET);
double initialGuess = promptForDouble(scanner, "Enter initial guess: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double result = Optimisation.newtonianOptimisation(userDefinedFunction, "x", initialGuess, tolerance, maxIterations);
System.out.printf(GREEN + "Newtonian Optimization Result: x = %.6f%n" + RESET, result);
}
}
private static void handleGradientDescent(Scanner scanner) throws Exception {
clearScreen();
drawBanner("GRADIENT DESCENT", GREEN);
if (userDefinedFunctionContainsVariable("y")) {
System.out.println(YELLOW + "\nMultivariable Gradient Descent" + RESET);
double xInitial = promptForDouble(scanner, "Enter initial x value: ");
double yInitial = promptForDouble(scanner, "Enter initial y value: ");
double learningRate = promptForDouble(scanner, "Enter learning rate: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double[] result = Optimisation.gradientDescentMultivariable(userDefinedFunction, learningRate, xInitial, yInitial, tolerance, maxIterations);
System.out.printf(GREEN + "Optimal point: (x=%.6f, y=%.6f)%n" + RESET, result[0], result[1]);
} else {
System.out.println(YELLOW + "\nSingle-variable Gradient Descent" + RESET);
double xInitial = promptForDouble(scanner, "Enter initial guess: ");
double learningRate = promptForDouble(scanner, "Enter learning rate: ");
double tolerance = promptForDouble(scanner, "Enter tolerance: ");
int maxIterations = promptForInt(scanner, "Enter max iterations: ");
double result = Optimisation.gradientDescent(userDefinedFunction, "x", learningRate, xInitial, tolerance, maxIterations);
System.out.printf(GREEN + "Gradient Descent Result: x = %.6f%n" + RESET, result);
}
}
}