Implemented and tested algorithm.

This commit is contained in:
Jonathan Turner 2024-02-15 13:41:33 -05:00
parent a66a462ced
commit 9c577f1330

View File

@ -33,9 +33,6 @@ Algorithm Design Block
return counter, comps
Big-O Analysis: (Based on Implementation)
*/
package Assignments.A2;
@ -50,6 +47,15 @@ import java.util.Scanner;
*/
public class Substrings {
public static void main(String[] args) {
Substrings program = new Substrings();
program.start();
}
private String text;
private int subStringCount;
private int comparisons;
/**
* Used as the main sentential loop and loops until the exit option is selected.
*
@ -73,7 +79,19 @@ public class Substrings {
* @param option the option that was chosen.
*/
private void executeOption(int option) {
performAlgorithm();
if (option == 1) {
this.text = this.getString();
} else {
if (this.text == null) {
System.out.println("Please specify a text to perform the algorithm.");
return;
}
this.performAlgorithm();
System.out.println("Input string: " + this.text);
System.out.println("# of substrings: " + this.subStringCount);
System.out.println("# of comparisons: " + this.comparisons);
}
System.out.println();
}
/**
@ -83,7 +101,21 @@ public class Substrings {
* @postcondition the results are generated.
*/
private void performAlgorithm() {
this.subStringCount = 0;
this.comparisons = 0;
char[] values = this.text.toLowerCase().toCharArray();
for (int i = 0; i < this.text.length(); i++) {
if (values[i] == 'a') {
for (int j = i+1; j < this.text.length(); j++) {
if (values[j] == 'b') {
subStringCount++;
}
comparisons++;
}
}
comparisons++;
}
}
/**
@ -124,6 +156,28 @@ public class Substrings {
System.out.println();
}
/**
* Gets a string and returns it. If the input is not valid it loops until valid.
*
* @precondition none
* @postcondition none
* @return a user-input text string.
*/
private String getString() {
System.out.println("Specify a text to check number of substrings.");
System.out.print("Text: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
while (input == null || input.isEmpty()) {
System.out.println("Please specify a valid text to check substrings.");
System.out.print("Text: ");
input = sc.nextLine();
}
return input;
}
/**
* Gets user input to a number. A prompt must be provided prior to running this method.
* If the input was not an integer/(unable to be autoboxed), returns -1.
@ -133,7 +187,7 @@ public class Substrings {
*
* @return the integer input, if invalid -1.
*/
protected int getIntegerInput() {
private int getIntegerInput() {
Scanner sc = new Scanner(System.in);
try {
String textInput = sc.nextLine();