-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.java
More file actions
928 lines (756 loc) · 39.2 KB
/
Copy pathUtility.java
File metadata and controls
928 lines (756 loc) · 39.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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//By Isaac Krabbenhoft
//Credits
//Java 2D Array Refference - https://www.codecademy.com/learn/learn-java/modules/java-two-dimensional-arrays/cheatsheet
//Max of a list - randomly poking around the Inteli-J IDE
//Checking for existence of key - randomly poking around the Inteli-J IDE
//Dealing with scanner input mismatch flushing - https://interviewkickstart.com/blogs/learn/scanner-reset-method-in-java
//Comparing hashmaps - https://stackoverflow.com/questions/663374/java-ordered-map#comment98922167_663396
//Making a copy of an array- https://www.linkedin.com/pulse/how-copy-arrays-java-ml-concepts-com
//Print array - https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array
//Removing duplicates from a list- https://www.geeksforgeeks.org/how-to-remove-duplicates-from-arraylist-in-java/
//HTML spacing - https://blog.dwac.dev/posts/html-whitespace/#html-whitespace-is-broken
//String multiplication - https://www.studytonight.com/java-examples/how-to-multiply-string-in-java
//How to trim whitespace from a string - https://www.scaler.com/topics/remove-whitespace-from-string-in-java/
package thecoachtoolapp;
import java.security.InvalidParameterException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.*;
public class Utility {
/**
* This function is to be used to generate a chart to the screen consisting of a line graph of a single
* Unicode character. The chart must be viewed in a monospace console. Other consoles will not work.
*
* @param width the width of the chart to be generated, must be a multiple of dataPoints
* @param height the height of the chart to be generated
* @param averageOver the number of units of data to average together to from a single data point
* @param dataPoints the number of data points to display
* @param line the Unicode character to use to display the line
* @param smoothConnectLines connects each part of the graph smoothly if set to true
* @param data the data to plot
* @throws InvalidParameterException triggered by negative data points or width not a multiple of dataPoints
*/
public static String printChart(int width, int height, int averageOver, int dataPoints, char line,
boolean smoothConnectLines, double[] data) throws InvalidParameterException {
//Verify that width is a multiple of dataPoints
if (width % dataPoints != 0) {
throw new InvalidParameterException("Error in call to Utility.printChart()!" +
"Width must be an integer multiple of dataPoints!");
}
//Verify that the caller has not supplied any negative arguments
if (Arrays.stream(data).min().getAsDouble() < 0) {
throw new InvalidParameterException("Error in call to Utility.printChart()!" +
"Must have only positive data points!");
}
//Initialize table with main data
char[][] chart = new char[height][width];
initTable(chart, width);
//Calculate the user requested averages
double[] processedData = new double[dataPoints];
int averageCounter = 0;
int lastIndex = 0;
//Outer loop keeps track of number of data points requested
for (int pointCounter = 0; pointCounter < dataPoints; pointCounter++) {
double currentSum = 0;
//Inner loop keeps track of individual numbers in dataset provided
//Looping to lastIndex + averageOver makes the next averageOver elements
//be averaged for each cycle of the outer loop.
for (; averageCounter < (lastIndex + averageOver); averageCounter++) {
currentSum += data[averageCounter];
}
lastIndex = averageCounter;
//Add the just generated average of data points to the processedData array
processedData[pointCounter] = (currentSum) / averageOver;
}
//Make a copy of processedData with all of its entries scaled so that the smallest is zero
double[] zeroBasedData = processedData.clone();
double minimum = Arrays.stream(processedData).min().getAsDouble();
//Loop over each entry of the copy and subtract the minimum value
for (int i = 0; i < zeroBasedData.length; i++) {
zeroBasedData[i] -= minimum;
}
//Calculate factor to scale entries by
double scalingFactor = (height) / Arrays.stream(zeroBasedData).max().getAsDouble();
//Generate the table using the processed data
if (!smoothConnectLines) {
//Loop over each column of the table
for (int colIndex = 0; colIndex < width; colIndex++) {
int rowIndex = getRowIndex(height, width, dataPoints, colIndex, scalingFactor, zeroBasedData);
chart[rowIndex][colIndex] = line;
}
} else {
//Initialize lastRowIndex
int lastRowIndex = getRowIndex(height, width, dataPoints, 0, scalingFactor, zeroBasedData);
//Loop over each column
for (int colIndex = 0; colIndex < width; colIndex++) {
//Find the current row index
int currentRowIndex = getRowIndex(height, width, dataPoints, colIndex, scalingFactor, zeroBasedData);
//Find the current and last row index to find the larger and smaller index
int bigRowIndex = Math.max(lastRowIndex, currentRowIndex);
int smallRowIndex = Math.min(lastRowIndex, currentRowIndex);
//Loop over each row within the given column from the smaller index to the larger one
for (; smallRowIndex <= bigRowIndex; smallRowIndex++) {
chart[smallRowIndex][colIndex] = line;
}
lastRowIndex = currentRowIndex;
}
}
//Call print table to do the final printing. Use .strip() to remove a trailing newline
return printTable(chart, width, processedData).strip();
}
/**
* The function generates a two-dimensional character array. It is a private helper function of printChart().
*
* @param chart is the chart to be printed
* @param columns is the number of columns in the chart
* @param chartData is the raw data contained within char
*/
private static String printTable(char[][] chart, int columns, double[] chartData) {
String stringRepresentation = "";
//Fetch chart axis
int[] axisLabels = generateAxisLabels(chartData, chart.length);
//Loop over each row of the table
for (int rowIndex = 0; rowIndex < chart.length; rowIndex++) {
//Determine the max length of the label and format every label to that length with preceding spaces
//Calculate the length of the longest number
int numberLength = Integer.toString(axisLabels[chart.length - 1]).length();
//Output each number formatted to that length
stringRepresentation += (numberFormat(numberLength,
axisLabels[chart.length - 1 - rowIndex]) + ". ");
//Loop over each column of the array
for (int colIndex = 0; colIndex < columns; colIndex++) {
stringRepresentation += (chart[rowIndex][colIndex]);
//Enter a newline at the end of each row of data
if (colIndex == (columns - 1)) {
stringRepresentation += ("\n");
}
}
}
return stringRepresentation;
}
/**
* This function generates axis labels for a chart given the data in the chart to calculate
* the span of numbers and the height of the chart to generate the right number of elements.
* This is a private helper function of printTable().
*
* @param chartData the data to be displayed in the chart
* @param chartHeight the height of the chart
* @return the axis labels for the chart
*/
private static int[] generateAxisLabels(double[] chartData, int chartHeight) {
//Largest and smallest elements
int[] indexLabels = new int[chartHeight];
double largestValue = Arrays.stream(chartData).max().getAsDouble();
double smallestValue = Arrays.stream(chartData).min().getAsDouble();
//Calculate what number each of the column indices should be a multiple of
double numericalSpan = largestValue - smallestValue;
double generatingFactor = numericalSpan / chartHeight;
//Loop once for each row of the chart and generate an axis label
for (int i = 0; i < chartHeight; i++) {
indexLabels[i] = (int) Math.round((generatingFactor * i) + smallestValue);
}
return indexLabels;
}
/**
* This function sets each element of a two-dimensional character array to the space character. It is a
* private helper function of printChart().
*
* @param chart the chart to have its elements set to ' '
* @param columns the number of columns in the chart
*/
private static void initTable(char[][] chart, int columns) {
//Loop over each row of the array
for (int rowIndex = 0; rowIndex < chart.length; rowIndex++) {
//Loop over each column of the table
for (int colIndex = 0; colIndex < columns; colIndex++) {
//Set each index to a space character
chart[rowIndex][colIndex] = ' ';
}
}
}
/**
* This function formats a number to a specified length by adding preceding spaces. It is a private helper function
* of printChart().
*
* @param lengthNeeded the needed number length
* @param number the number for format
* @return the formatting number as a String
*/
private static String numberFormat(int lengthNeeded, double number) {
//Convert the supplied double to a string for returning
String numberString = Integer.toString((int) Math.round(number));
//Calculate actual length of number
int currentLength = numberString.length();
//Calculate how many preceding spaces to add
int lengthDifference = lengthNeeded - currentLength;
//Append spaces to the begining of the current string to cause it to align when displayed
numberString = " ".repeat(lengthDifference) + numberString;
return numberString;
}
/**
* This function calculates the row index to place an element of an array at. It needs the chart's width
* and total number of data points to calculate the ratio of the column indices to the length of the
* array that they are being mapped to. The column index is in the calculation of which element of the supplied
* array of processedData to access. The scaling factor scales the value found at the calculated index to the
* correct height. The maximum height is needed for clamping. This is a private helper function of getChart().
*
* @param height the height of the chart in question
* @param width the width of the chart in question
* @param dataPoints the number of data points being displayed on the chart in question
* @param colIndex the column index to calculate the row index of
* @param scalingFactor the factor to multiply the value found in processedData by to make it fit the height
* @param processedData the array containing the potential values to use in finding the row index
* @return the index specified by the data provided
*/
private static int getRowIndex(int height, int width, int dataPoints, int colIndex,
double scalingFactor, double[] processedData) {
//Calculate the row index to update based the magnitude of the current datapoint
//Calculate what multiple of the length of dataPoints width is
int widthMultiple = (width / dataPoints);
//Calculate which index of processedData to access. Subtracting 0.1 and dividing by the widthMultiple
//maps each index of width to the corresponding index of the potentially shorter list processed data.
int processedDataIndex = (int) ((colIndex - 0.1) / widthMultiple);
//Compute the relative magnitude of the data point at the calculated index of processedData
int relativeMagnitude = (int) (processedData[processedDataIndex] * scalingFactor);
//Calculate the rowIndex by subtracting relative magnitude from the height to invert the chart so
//that it displays right side up. Clamping prevents out of bounds errors.
return (Math.clamp((height - relativeMagnitude), 0, height - 1));
}
/**
* This function gets a string of input from the user. The initial prompt is given. If the user inputs something
* invalid (iether outside checkAgainst with invertChecking false or inside checkAgainst with invertChecking true),
* then the user is prompted again with errorPrompt until valid input is given.
* The prompts can contain the special charecter ~ which will be replaced with the ellements of the list
* mustBeIn.
*
* @param scnr the scanner to read the input with
* @param prompt the initial prompt
* @param errorPrompt the prompt if the user inputs something not in the list mustBeIn
* @param checkAgainst the list to check all supplied strings against.
* @param invertChecking whether to get an item not in the supplied list
* @return the user supplied string within mustBeIn
*/
public static String getString(Scanner scnr, String prompt, String errorPrompt, String[] checkAgainst,
boolean invertChecking) {
//Get initial value
System.out.println(getMessage(prompt, checkAgainst));
String retVal = getString(scnr);
//Generate error message
String errorMessage = getMessage(errorPrompt, checkAgainst);
//If checking is not inverted, loop until a value in the list is entered
if (!invertChecking) {
//Check if the last value is in the list
while (!isInStringList(retVal, checkAgainst)) {
//Get a new value if the user entered a value in the list
System.out.println(errorMessage);
retVal = getString(scnr);
}
//If checking is inverted, loop until a value not in the list is entered
} else {
//Check if the last value is in the list
while (isInStringList(retVal, checkAgainst)) {
//Get a new value if the user entered a value in the list
System.out.println(errorMessage);
retVal = getString(scnr);
}
}
return retVal;
}
/**
* This function gets THE INDEX OF a string of input from the user.
* The initial prompt is given. If the user inputs something
* invalid (either outside checkAgainst with invertChecking false or inside checkAgainst with invertChecking true),
* then the user is prompted again with errorPrompt until valid input is given.
* The prompts can contain the special character ~ which will be replaced with the elements of the list
* mustBeIn.
*
* @param scnr the scanner to read the input with
* @param prompt the initial prompt
* @param errorPrompt the prompt if the user inputs something not in the list mustBeIn
* @param checkAgainst the list to check all supplied strings against.
* @return the user supplied string within mustBeIn
*/
public static int getStringIndex(Scanner scnr, String prompt, String errorPrompt, String[] checkAgainst) {
//Create the return value
int currentIndex = -1;
//Get initial value
System.out.println(getMessage(prompt, checkAgainst));
//Generate error message
String errorMessage = getMessage(errorPrompt, checkAgainst);
//Do first prompt so error message isn't displayed if possible
currentIndex = indexInList(scnr.nextLine(), checkAgainst);
//Check if the last value is in the list
while (currentIndex == -1) {
//Get a new value if the user entered a value in the list
System.out.println(errorMessage);
currentIndex = indexInList(scnr.nextLine(), checkAgainst);
}
return currentIndex;
}
/**
* This function gets a string of input from the user at least one character long. This is a private helper
* function of getString() with additional arguments.
*
* @param scnr the scanner to read the input with
* @return a string of length greater than zero
*/
private static String getString(Scanner scnr) {
String retVal = scnr.nextLine();
//Loop until the user supplies a string of length greater than zero.
while (retVal.length() == 0) {
System.out.println("Your input must be at least one character in length:");
retVal = scnr.nextLine();
}
return retVal;
}
/**
* This function gets a string of input from the user at least one character long. It displays a prompt and then
* reads the user's input.
*
* @param scnr the scanner to read the input with
* @return a string of length greater than zero
*/
public static String getString(Scanner scnr, String prompt) {
System.out.println(prompt);
String retVal = scnr.nextLine();
//Loop until the user supplies a string of length greater than zero.
while (retVal.length() == 0) {
System.out.println("Your input must be at least one character in length:");
retVal = scnr.nextLine();
}
return retVal;
}
/**
* This function gets a double from the user. It outputs an error message if a non-double is entered.
*
* @param scnr the scanner to read the integer with
* @param errorPrompt the prompt to give the user if they input an out-of-bounds number
* @return the user entered integer between minInclusive and maxInclusive inclusive
*/
public static double getDoubleNoPrompt(Scanner scnr, String errorPrompt) {
//Program logic guarantees that this will have a value by the time any meaningfully inferences about
//its contents are made, but the compiler doesn't recognize this, so setting a default value is necessary.
double userDouble = 0;
//This boolean tracks if the user has supplied an integer value. If this value is false then
//short-circuiting prevents any comparisons being made on userInteger.
boolean hasDouble = false;
//Loop until the user inputs something that is an integer and is in the desired range
while (!hasDouble) {
//Attempt to get an integer input from the user
try {
userDouble = scnr.nextDouble();
hasDouble = true;
}
//If the user inputting something that isn't a number, output an error message
catch (Exception e) {
//Set hasDouble to false to get a new number from the user
hasDouble = false;
System.out.println(errorPrompt);
//Clear bad input from the input stream
scnr.nextLine();
}
}
return userDouble;
}
/**
* This function gets an array list of strings that are members of an array of strings from the user. mainPrompt
* is displayed once and errorPrompt is displayed each time the user inputs a string not in the list mustBeIn
*
* @param scnr the scanner to read the input with
* @param mainPrompt the prompt the display at the beginning of reading the input
* @param errorPrompt the prompt to display when the user enters a string not in mustBeIn
* @param mustBeIn the list of strings that each user supplied string must be within
* @return the ArrayList of user supplied strings
*/
public static ArrayList<String> getList(Scanner scnr, String mainPrompt, String errorPrompt, String[] mustBeIn) {
ArrayList<String> userStrings = new ArrayList<>();
String input;
//Formulate the error prompt
String generatedErrorPrompt = getMessage(errorPrompt, mustBeIn);
//Display main prompt
System.out.println(getMessage(mainPrompt, mustBeIn));
//Get list from user
do {
input = scnr.nextLine();
//Add input to list if its valid
if (isInStringList(input, mustBeIn)) {
userStrings.add(input);
}
//Output error prompt if input is invalid and user is not ending list
else if (!input.equals("-1")) {
System.out.println(generatedErrorPrompt);
}
//If the user is attempting to not input any values then output an error message
else if (userStrings.size() == 0) {
System.out.println("Error: list must have at least one entry: ");
}
}
//Continue until user ends non-empty list with "-1"
while (!input.equals("-1") || userStrings.size() == 0);
//Remove duplicates
return removeDuplicates(userStrings);
}
/**
* This function gets an array list of objects that are members of an array of strings from the user. mainPrompt
* is displayed once and errorPrompt is displayed each time the user inputs a string not in the list mustBeIn
*
* @param scnr the scanner to read the input with
* @param mainPrompt the prompt the display at the beginning of reading the input
* @param errorPrompt the prompt to display when the user enters a string not in mustBeIn
* @param mustBeIn the list of objects that each user supplied string must be within
* @return the ArrayList of user supplied strings
*/
public static <ItemType extends NamedResource> ArrayList<ItemType>
getObjectList(Scanner scnr, String mainPrompt, String errorPrompt, ArrayList<ItemType> mustBeIn) {
String[] mustBeInStrings = NamedResource.getStringsFromList(mustBeIn);
ArrayList<ItemType> userObjects = new ArrayList<>();
String input;
//Formulate the error prompt
String generatedErrorPrompt = getMessage(errorPrompt, mustBeInStrings);
//Display main prompt
System.out.println(getMessage(mainPrompt, mustBeInStrings));
//Get list from user
do {
input = scnr.nextLine();
//Add input to list if its valid
if (isInStringList(input, mustBeInStrings)) {
try {
userObjects.add(NamedResource.getItemByName(input, mustBeIn));
} catch (Exception e) {
System.out.println("Error, could not convert string to object");
System.out.println(e.getMessage());
}
}
//Output error prompt if input is invalid and user is not ending list
else if (!input.equals("-1")) {
System.out.println(generatedErrorPrompt);
}
//If the user is attempting to not input any values then output an error message
else if (userObjects.size() == 0) {
System.out.println("Error: list must have at least one entry: ");
}
}
//Continue until user ends non-empty list with "-1"
while (!input.equals("-1") || userObjects.size() == 0);
//Remove duplicates
return (ArrayList<ItemType>) userObjects.stream().distinct().collect(Collectors.toList());
}
/**
* This function gets an array list of objects that are members of an array of strings from the user. mainPrompt
* is displayed once and errorPrompt is displayed each time the user inputs a string not in the list mustBeIn
*
* @param scnr the scanner to read the input with
* @param mainPrompt the prompt the display at the beginning of reading the input
* @param errorPrompt the prompt to display when the user enters a string not in mustBeIn
* @param mustBeIn the list of objects that each user supplied string must be within
* @return the ArrayList of user supplied strings
*/
public static <ItemType extends NamedResource> ItemType
getObject(Scanner scnr, String mainPrompt, String errorPrompt, ArrayList<ItemType> mustBeIn) {
String[] mustBeInStrings = NamedResource.getStringsFromList(mustBeIn);
ItemType userObject = null;
String input;
//Formulate the error prompt
String generatedErrorPrompt = getMessage(errorPrompt, mustBeInStrings);
//Display main prompt
System.out.println(getMessage(mainPrompt, mustBeInStrings));
//Get list from user
do {
input = scnr.nextLine();
//Add input to list if its valid
if (isInStringList(input, mustBeInStrings)) {
try {
userObject = NamedResource.getItemByName(input, mustBeIn);
} catch (Exception e) {
System.out.println("Error, could not convert string to object");
System.out.println(e.getMessage());
}
} else {
System.out.println(generatedErrorPrompt);
}
}
//Continue until user ends non-empty list with "-1"
while (userObject == null);
//Remove duplicates
return userObject;
}
/**
* This function gets an array list of strings from the user. The do not have to me members of any list
* and none is taken in by this function.
*
* @param scnr the scanner to read the input with
* @param mainPrompt the prompt the display at the beginning of reading the input
* @return the ArrayList of user supplied strings
*/
public static ArrayList<String> getList(Scanner scnr, String mainPrompt) {
ArrayList<String> userStrings = new ArrayList<>();
String input;
//Display main prompt
System.out.println(mainPrompt);
//Get list from user
do {
//Get and add a single string to the list
input = getString(scnr);
if(! input.equals("-1")) {
userStrings.add(input);
}
//If the user is attempting to not input any values then output an error message
if (input.equals("-1") && userStrings.size() == 0) {
System.out.println("Error: list must have at least one entry: ");
}
}
//Continue until user ends non-empty list with "-1"
while (!input.equals("-1") || userStrings.size() == 0);
//Remove duplicates
return removeDuplicates(userStrings);
}
/**
* This function takes an array list of strings and removes the first instances of any duplicate in a case
* insensitive manner. It is a private helper function of getList().
*
* @param stringList the arrayList to remove the duplicates from
*/
public static ArrayList<String> removeDuplicates(ArrayList<String> stringList) {
ArrayList<String> noDuplicates = new ArrayList<>();
//Loop over each element of the string list
for (int outerLoopChecker = 0; outerLoopChecker < stringList.size(); outerLoopChecker++) {
//Default the variable to check for a duplicate to false
boolean duplicateFound = false;
//Get the current word to check against
String currentOuterWord = stringList.get(outerLoopChecker);
//Loop until a duplicate is found. Start looping here from the index of the outer loop + 1 so that the
//current word does not detect itself as a duplicate. The loop will not go out of bounds in this way
//because for loops are pre-test loops in Java
for (int innerLoopChecker = outerLoopChecker + 1; innerLoopChecker < stringList.size() && !duplicateFound;
innerLoopChecker++) {
if (currentOuterWord.toLowerCase().equals(stringList.get(innerLoopChecker).toLowerCase())) {
duplicateFound = true;
}
}
//If no later duplicate was found in the list, then add the current instance of the word to the return
//value variable noDuplicates
if (!duplicateFound) {
noDuplicates.add(currentOuterWord);
}
}
return noDuplicates;
}
/**
* This function gets a LinkedHashMap that associates a user inputted label with a user-inputted list of Strings.
* Label prompt is displayed for each label and innerPrompt is displayed for each sublist. innerErrorPrompt is
* displayed each time the user inputs an invalid item to be added to the inner list.
*
* @param scnr the scanner to read input with
* @param labelPrompt the string to prompt the user for a label of the current list with
* @param innerPrompt the string to prompt the user for each sublist with
* @param innerErrorPrompt the string to notify the user that their entry into the sublist is invalid
* @param innerMustBeIn the list that the entries of the sublist must be in
* @return the user's labels and lists organized in a LinkedHashMap
*/
public static <DataType extends NamedResource> LinkedHashMap<String, ArrayList<DataType>> getNested
(Scanner scnr, String labelPrompt, String innerPrompt, String innerErrorPrompt,
ArrayList<DataType> innerMustBeIn) {
//Formulate strings corresponding to objects to search for
String[] innerMustBeInStrings = NamedResource.getStringsFromList(innerMustBeIn);
//Create a new hashMap to use as a return value
LinkedHashMap<String, ArrayList<DataType>> userHashOfLists = new LinkedHashMap<>();
//Create reusable variables for the keys and values of the return value
ArrayList<String> currentSublist;
String currentSublistLabel;
//Get each key value pair from the user for the hashmap
do {
//Get the String key from the user
System.out.println(labelPrompt);
currentSublistLabel = getString(scnr);
//Proceed to get the value ArrayList<String> from the user if the name wasn't supplied as "-1" or
//a key that already exists
if (!currentSublistLabel.equals("-1") && !userHashOfLists.containsKey(currentSublistLabel)) {
//Get the next list from the user and add it to the return value
currentSublist = getList(scnr, innerPrompt, innerErrorPrompt, innerMustBeInStrings);
try {
userHashOfLists.put(currentSublistLabel,
NamedResource.getItemsByNames(currentSublist,
innerMustBeIn));
} catch (Exception e) {
System.out.println("Error, could not match all supplied names to objects");
}
}
//Notify the user if they attempt to reuse a key
else if (userHashOfLists.containsKey(currentSublistLabel)) {
System.out.println("Error: that name was already used:");
}
//If the flow of control is here then the user has entered -1
//Output an error message if the user is trying to input an empty list
else if (userHashOfLists.size() == 0) {
System.out.println("Error: list must have at least one entry:");
}
}
//Loop until the user enters "-1" as the label of the current list
while (!currentSublistLabel.equals("-1") || userHashOfLists.size() == 0);
return userHashOfLists;
}
/**
* This function determines if a String is contained within an array of Strings. It is a private helper function
* of getString() that returns a string.
*
* @param match the String to attempt to find in the list
* @param matchTo the array to attempt to find the string in
* @return whether the supplied String was found in the supplied arrays of Strings
*/
private static boolean isInStringList(String match, String[] matchTo) {
//Default found to false
boolean found = false;
//Loop until the list ends or the String is found
for (int i = 0; i < matchTo.length && !found; i++) {
//Check if each element of the list is equal to the supplied string
if (match.toLowerCase().equals(matchTo[i].toLowerCase())) {
found = true;
}
}
return found;
}
/**
* This function that gets the index of a string in a list of strings or returns -1. It is a private
* helper function of the getString() that returns an integer.
*
* @param match the String to attempt to find in the list
* @param matchTo the array to attempt to find the string in
* @return whether the supplied String was found in the supplied arrays of Strings
*/
private static int indexInList(String match, String[] matchTo) {
//Default the index to the error case
int foundIndex = -1;
//Default found to false
boolean found = false;
//Loop until the list ends or the String is found
for (int i = 0; i < matchTo.length && !found; i++) {
//Check if each element of the list is equal to the supplied string
if (match.toLowerCase().equals(matchTo[i].toLowerCase())) {
found = true;
foundIndex = i;
}
}
return foundIndex;
}
/**
* Formats a string so that each occurance of ~ is replaced with a list of strings. This is used by functions
* for getting user input in Utility and also inside of the main class for output formating.
*
* @param basicMessage the message to format
* @param augmentingList the list to insert
* @return the formatted message
*/
public static String getMessage(String basicMessage, String[] augmentingList) {
//Parse the supplied list to a string
String augmentListString = Arrays.toString(augmentingList);
//Remove brackets from the string
try{
augmentListString = augmentListString.substring(1, augmentListString.length() - 1);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error, attempting to format an empty list. This list should have data in it. " +
"Responding by returning an empty string from this sub-operation.");
System.out.println(e.getMessage());
augmentListString = "";
}
//Replace "~" with the generated string
return basicMessage.replace("~", augmentListString);
}
/**
* This function parses a list and returns it in a printable form using Arrays.toString()
* and .substring()
*
* @param augmentingList the list to format
* @return the formatted list
*/
public static String getFormattedList(String[] augmentingList) {
//Parse the supplied list to a string
String augmentListString = Arrays.toString(augmentingList);
//Remove brackets from the string
try{
augmentListString = augmentListString.substring(1, augmentListString.length() - 1);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error, attempting to format an empty list. This list should have data in it. " +
"Responding by returning an empty string.");
System.out.println(e.getMessage());
augmentListString = "";
}
//Replace "~" with the generated string
return augmentListString;
}
/**
* This function parses a list and returns it in a printable form using Arrays.toString()
* and .substring()
*
* @param augmentingList the list to format
* @return the formatted list
*/
public static String getFormattedList(double[] augmentingList) {
//Parse the supplied list to a string
String augmentListString = Arrays.toString(augmentingList);
//Remove brackets from the string
try{
augmentListString = augmentListString.substring(1, augmentListString.length() - 1);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error, attempting to format an empty list. This list should have data in it. " +
"Responding by returning an empty string.");
System.out.println(e.getMessage());
augmentListString = "";
}
//Replace "~" with the generated string
return augmentListString;
}
/**
* This function reads in a list of doubles of a specified length. If a string that cannot be interpreted as a
* double is entered, an error message is displayed.
*
* @param scnr the scanner to read input with
* @param mainPrompt the prompt to display initially to ask for the list of numbers
* @param errorPrompt the prompt to display if a non-numeric entry is received
* @param dataLength the number of numbers to read in
* @return the data read from the user
*/
public static double[] getDoubleList(Scanner scnr, String mainPrompt, String errorPrompt, int dataLength) {
double[] dataArray = new double[dataLength];
System.out.println(mainPrompt);
for(int i = 0; i < dataLength; i++) {
dataArray[i] = getDoubleNoPrompt(scnr, errorPrompt);
}
return dataArray;
}
/**
* This function is used by the callers of getChart() in order to determine with width of the
* axis labels generated and to therefore be able to shift the independent variable labels
* appropriately.
* @param inputWithNumber the input containing numbers assumed to represent dependent variable axis labels
* @return an integer representing the proper offset
*/
public static int getOffsetLength(String inputWithNumber) {
//Create a pattern to match a number
Pattern digitFinder = Pattern.compile("\\d+");
//Create a matcher to run this pattern against the chart
Matcher getDigit = digitFinder.matcher(inputWithNumber);
//Get the first digit in the chart
getDigit.find();
//Find the length of the first digit
int labelSize = getDigit.group().length();
//Compute length of shifting to the right needed as the number length pluss two which represent the ". "
//at the beggining of each line
return (labelSize + 2);
}
/**
* This function uses a lambda to replace a string within a list of strings.
*
* @param stringToRemove the string to remove
* @param replacementString the string to replace it with
* @param removeFrom the dataset to be cleaned
* @return the cleaned dataset
*/
public static String[] removeChar(String stringToRemove, String replacementString, String[] removeFrom) {
ArrayList<String> withCharArrayList = new ArrayList<>(Arrays.asList(removeFrom));
ArrayList<String> withoutCharArrayList = new ArrayList<>();
withCharArrayList.forEach((String currentWord) ->
{withoutCharArrayList.add(currentWord.replace(stringToRemove, replacementString));});
return withoutCharArrayList.toArray(new String[0]);
}
}