r/JavaProgramming • • 4d 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();
   }

}
3 Upvotes

4 comments sorted by

1

u/Substantial_Code_914 4d ago

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

1

u/XIA_Biologicals_WVSU 3d ago

Yeah. I love coding with AI because it can help me out when I get stuck, which is cool and makes learning that much faster.

1

u/XIA_Biologicals_WVSU 3d ago

This is what I got now. I did have to use AI to primarily program this part of the program, but that's fine: I'm learning.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;

public class MiniLanguageModel {

    // Stores words and the words that follow them
    static HashMap<String, ArrayList<String>> 
brain 
= new HashMap<>();

    // Stores all known vocabulary
    static HashSet<String> 
vocabulary 
= new HashSet<>();

    static Random 
random 
= new Random();

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.
in
);

        // Starter knowledge
        
train
("the quick brown fox jumps over the lazy dog", false);
        
train
("the dog barks at the fox in the yard", false);
        
train
("hello how are you", false);
        
train
("i am a mini language model", false);
        
train
("artificial intelligence can learn new words", false);

        System.
out
.println("=== Mini-AI Ready ===");
        System.
out
.println("I can learn words and generate sentences.");

        System.
out
.println("\nCommands:");
        System.
out
.println("learn <text> - Teach the AI");
        System.
out
.println("vocab        - Show vocabulary");
        System.
out
.println("chat         - Generate a sentence");
        System.
out
.println("generate     - Generate a random sentence");
        System.
out
.println("exit         - Close the program");

        while (true) {

            System.
out
.print("\nYou: ");

            String input = scanner.nextLine().trim();

            if (input.equalsIgnoreCase("exit")) {
                System.
out
.println("AI: Goodbye!");
                break;
            }

            else if (input.equalsIgnoreCase("vocab")) {
                
displayVocabulary
();
            }

            else if (input.equalsIgnoreCase("chat")) {

                System.
out
.print("Starting word: ");

                String seed = scanner.nextLine()
                        .toLowerCase()
                        .trim();

                System.
out
.println("AI: " + 
generateSentence
(seed, 12));
            }

            else if (input.equalsIgnoreCase("generate")) {

                System.
out
.println("AI: " + 
generateRandomSentence
(12));
            }

            else if (input.toLowerCase().startsWith("learn ")) {

                String sentence = input.substring(6).trim();

                if (!sentence.isEmpty()) {
                    
train
(sentence, true);
                    System.
out
.println("AI: I learned something new!");
                }
            }

            else if (!input.isEmpty()) {

                
train
(input, true);

                System.
out
.println("AI: I have learned your sentence.");
            }
        }

        scanner.close();
    }

    // Train the AI
    public static void train(String text, boolean showFeedback) {

        String cleaned = text.toLowerCase()
                .replaceAll("[^a-z0-9\\s]", "")
                .trim();

        if (cleaned.isEmpty()) {
            return;
        }

        String[] tokens = cleaned.split("\\s+");

        for (String word : tokens) {
            
vocabulary
.add(word);
        }

        // Learn word relationships
        for (int i = 0; i < tokens.length - 1; i++) {

            String currentWord = tokens[i];
            String nextWord = tokens[i + 1];

            
brain
.putIfAbsent(currentWord, new ArrayList<>());

            
brain
.get(currentWord).add(nextWord);

            if (showFeedback) {
                System.
out
.println(
                        "  Learned connection: "
                                + currentWord + " -> " + nextWord
                );
            }
        }
    }

    // Generate a sentence from a starting word
    public static String generateSentence(String seed, int maxWords) {

        seed = seed.toLowerCase().trim();

        if (!
vocabulary
.contains(seed)) {
            return "I don't know that word yet. Teach me using learn <text>!";
        }

        StringBuilder sentence = new StringBuilder(seed);

        String currentWord = seed;

        for (int i = 1; i < maxWords; i++) {

            ArrayList<String> possibleWords = 
brain
.get(currentWord);

            if (possibleWords == null || possibleWords.isEmpty()) {
                break;
            }

            String nextWord = possibleWords.get(
                    
random
.nextInt(possibleWords.size())
            );

            sentence.append(" ").append(nextWord);

            currentWord = nextWord;
        }

        return 
capitalize
(sentence.toString()) + ".";
    }

    // Generate a sentence using a random starting word
    public static String generateRandomSentence(int maxWords) {

        if (
vocabulary
.isEmpty()) {
            return "I don't know any words yet!";
        }

        ArrayList<String> words = new ArrayList<>(
vocabulary
);

        String seed = words.get(
random
.nextInt(words.size()));

        return 
generateSentence
(seed, maxWords);
    }

    // Display vocabulary
    public static void displayVocabulary() {

        System.
out
.println("\n=== AI Vocabulary ===");

        if (
vocabulary
.isEmpty()) {
            System.
out
.println("No words learned yet.");
            return;
        }

        ArrayList<String> words = new ArrayList<>(
vocabulary
);

        words.sort(String::compareTo);

        for (String word : words) {
            System.
out
.println("- " + word);
        }

        System.
out
.println("\nTotal words: " + 
vocabulary
.size());
    }

    // Capitalize first letter
    public static String capitalize(String text) {

        if (text == null || text.isEmpty()) {
            return text;
        }

        return text.substring(0, 1).toUpperCase()
                + text.substring(1);
    }
}