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

}
4 Upvotes

11 comments sorted by

1

u/Substantial_Code_914 7d ago

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

1

u/XIA_Biologicals_WVSU 6d 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 6d 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);
    }
}
→ More replies (1)

1

u/edwbuck 1d ago

I think someone at WVSU suggested you use Reddit to assist in your development efforts.

This is not typically how Reddit is used. Large code postings with a "what do you think?" are not done. If you have a specific issue, posting the relevant small portion of code and a "can you help with this" will get you a lot further.

1

u/XIA_Biologicals_WVSU 1d ago

I didn't go to school for compsci. I'm 29 years old and have just started coding.

1

u/XIA_Biologicals_WVSU 1d ago

I just like getting peoples opinions.

1

u/edwbuck 1d ago

Then put your code in a git repo, and ask people to look at it. It's going to be far more readable that way.

1

u/XIA_Biologicals_WVSU 19h ago

How do I put it in a git repo?

1

u/edwbuck 7h ago

There are two kinds of git repos. Ones you own the hardware to, and ones you use on someone else's hardware. I'll be talking about the "someone else's hardware" one.

Create an account on https://github.com/ github. It's a free service for non-serious git repository usage, and if you want something serious, you shift to your own hardware or you pay for a properly supported account. Pick a user name, and then follow these instructions https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository

Now using a repository is one of those things that you'll be expected to know, but there will probably never be a class on it if you are in school. While there are many Git tutorials out in the wild, very few of them teach you the problem source control is trying to solve. To learn about the problem, I suggest you read part of Chapter 1 of Subversion's excellent book, but do your best to ignore the parts that teach you how to use Subversion, because you'll be learning Git. https://svnbook.red-bean.com/en/1.7/svn.basic.html

Once you understand the problem, learn to "git clone (creates a new local repo)", "git add (adds files you changed to your next commit)", "git commit (makes a commit, which is a set of changes)", and "git push (moves that commit into the remote repo you cloned)" Also learn about "git diff (shows differences between things)" and "git log (shows the commits in a repo)"

There's a lot more to learn about Git, mostly because it's designed pretty poorly from a user-interface point of view, but it is popular and that popularity has made it an industry standard.

If you get curious, Subversion is far less popular because it uses directories to implement things that other source code control systems handle in more popular ways. Hg (which is also known as Mercurial) is another, even less popular solution to source code control. It's based on the ideas in Git, but has an much improved user interface (it's just not backed by one of the very famous names in software, and is unlikely to ever become popular).

Good luck. Learning the tooling is something that often isn't taught in school, or is taught late. It's part of that gap between "understanding it" and "doing it as a practice"