r/JavaProgramming • • 4d ago

This is a little program that I created with the help of AI

This is a little program that I created with the help of AI. I only used AI when I became stuck on certain parts of the program. The program allows the user to input a file directly into the IDE, whcich allows the terminal to output what is in the file; it also allows the user to select a file to read, and finally allows the user to select a place to save a file and enter text to be saved into a file. 



import javax.swing.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.awt.Desktop;
import java.util.Scanner;

import static java.awt.SystemColor.
text
;

class newProject {
    public static void main(String[] args) throws IOException {

        // capture user input:

        Scanner scanner = new Scanner(System.
in
);
        String UserData = scanner.nextLine();
        System.
out
.println(UserData);

        if (UserData.equals("1")) {

            Files.
lines
(Path.
of
("C:/Users/zgarr/OneDrive/Desktop/text.txt"))
                    .forEach(System.
out
::println);

        } else if (UserData.equals("2")) {

            File directory = new File("C://documents");

            try {
                ProcessBuilder explorer = new ProcessBuilder(
                        "explorer.exe",
                        directory.getAbsolutePath()
                );

                explorer.start();

                // User selection for number 2

            } catch (IOException e) {
                e.printStackTrace();
            }

        } else if (UserData.equals("3")) {

            System.
out
.print("Enter a name for your file");
            String fileName = scanner.nextLine();
            if (!fileName.endsWith(".txt")) {
                fileName += ".txt";
            }

            String folder = 
chooseSaveFolder
();
            File fullPath = new File(folder, fileName);

            System.
out
.println("Start typing your text to save it. Type exit when finished");

            try (FileWriter writer = new FileWriter(fullPath)) {

                while (true) {
                    String line = scanner.nextLine();

                    if (line.equalsIgnoreCase("EXIT")) {
                        break;
                    }
                    writer.write(line + System.
lineSeparator
());
                }
                System.
out
.println("saved doucment too " + fullPath);
            } catch (IOException e) {
                System.
out
.println("Error saving file" + e.getMessage());
            }

        } else {

            System.
out
.println("Wrong selection");

        }

        scanner.close();

    }

// This method helps the user select a place to save the file

    public static String chooseSaveFolder() {

        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Select a folder to save your file");
        chooser.setFileSelectionMode(JFileChooser.
DIRECTORIES_ONLY
);

        int result = chooser.showSaveDialog(null);
        if (result == JFileChooser.
APPROVE_OPTION
) {
            return chooser.getSelectedFile().getAbsolutePath();

        }
        return ".";
    }
}
2 Upvotes

6 comments sorted by

1

u/ChaoticHippo 4d ago

r/programminghorror
What's up with the formatting? The varying indentation styles (I'm assuming from copy/pasting from AI output) is incredibly hard to read / follow. If you're going to do multiple lines from dot operators, it should look like:

System.out
    .println("...");

// Not
    System.
out.
println("..."
);

// This is the worst offendor tbh:
        Scanner scanner = new Scanner(System.
in
);

I also would not do this with something as simple as a Scanner or print statement. This formatting is generally best for deeply nested calls:

Dataset<Row> ratings = spark.read()
    .format("csv")
    .option("header", "true")
    .option("inferSchema", "true")
    .load(inputPath);

2

u/XIA_Biologicals_WVSU 4d ago

Ok. Thanks for the reply. No. the formatting does not look like that in my IDE

3

u/XIA_Biologicals_WVSU 4d ago

I think when I copied it from the IDE it screwed up the formatting.

1

u/ChaoticHippo 4d ago

I gotcha - yeah very hard to follow on here lol

1

u/XIA_Biologicals_WVSU 4d ago

Next post I make, I'll make sure its formatted properly. Do you do coding lessons? I know some people on here do. I'd love to learn more. I still have to have help from google and chatGPT to make what I want to make.

1

u/ChaoticHippo 4d ago

I do not - sorry! I can recommend Coding with John on YouTube for learning Java concepts though. I found the way he describes and explains things very helpful for things like generics, lambdas, and optionals.

Sorry for calling out your formatting without giving you a commendation though - that's a cool project to have built while you're learning. File I/O can be annoying early, and it's a good fundamental skill to get down since most programs will require it.

Don't sweat needing to Google things, but I would recommend trying to ween off of relying on AI generated code if you are trying to learn how to do it, and go more towards using Google / AI just to give you the broad overview and suggest libraries or tools, and then dig into documentation for how to actually implement things. For example, allow your prompting to get you to "I should use a Scanner to take the file in," and then go to JavaDocs for the Scanner object and see how you can use it.

Being able to get your answer from documentation is super useful, especially once you start using things that are not core libraries (for example, if you're extending another programmer's code).