r/JavaProgramming • • 11h ago

A cool little program (thinking about what to do with it next and how to add stuff to it).

This is a cool little program I made using some for loops and other stuff. The idea is mine: I built it from the first two for loops and then used chatGPt for other ideas. Most of the code is original and only some ideas are from chatGPT. I thinking using AI has helped my learn faster, rather than learning from documentation alone. 


import java.util.Scanner;
import java.util.ArrayList;

void main(String[] args) {

    System.
out
.print("Enter a sentence: ");
    Scanner scanner = new Scanner(System.
in
);

    String i = scanner.nextLine();
    String[] tokens = i.trim().split("\\s+");

    ArrayList<String> list = new ArrayList<>();

    for (int x = 0; x < tokens.length; x++) {
        list.add(tokens[x]);
    }

    String[][] arraytwo = new String[list.size()][2];

    int rows = 0;

    // Check each word
    for (int j = 0; j < list.size(); j++) {

        String word = list.get(j);
        boolean found = false;

        // Check if word is already in the 2D array
        for (int y = 0; y < rows; y++) {

            if (word.equalsIgnoreCase(arraytwo[y][0])) {
                found = true;

                int occurrences = Integer.
parseInt
(arraytwo[y][1]);
                occurrences++;

                arraytwo[y][1] = String.
valueOf
(occurrences);
                break;
            }
        }

        // If word is not found, add it
        if (!found) {
            arraytwo[rows][0] = word;
            arraytwo[rows][1] = "1";
            rows++;
        }
    }

    // Display results
    for (int j = 0; j < rows; j++) {
        System.
out
.println(
                arraytwo[j][0] + " appears " +
                        arraytwo[j][1] + " times."
        );
    }

    System.
out
.println("Total words: " + list.size());

    scanner.close();
   }

}
1 Upvotes

1 comment sorted by

1

u/Substantial_Code_914 7h ago

Nice project! Adding input validation and more useful features could make it even better.