#CLI - Challenge 4

1 messages · Page 1 of 1 (latest)

jaunty niche
#

Alright so I've been trying to come up with a solution and I am having a bit of trouble. Hoping someone can point me in the right direction here.

If a -d argument is provided then, instead of printing the result, the program should write the result to a file at the specified path.

So java src/CLI.java -d out.txt 9 should write 81 into a file named out.txt. The order that -d and --operation are provided should not matter. java src/CLI.java -d out.txt --operation factorial 3 and java src/CLI.java --operation factorial -d out.txt 3 should behave exactly the same.

What I have works with the previous challenge. The two big glaring issues is how to handle the order in which the commands are given and then writing to a file the value provided. I was going to look up how to write to a file (since I don't believe that was covered yet) The bigger issue I am struggling with is how to handle the commands in which I receive them. I also probably need to setup an enum or something if I ever want to expand my available commands.

snow cosmosBOT
#

<@&987246399047479336> please have a look, thanks.

jaunty niche
#
class CLI {
    boolean isInteger(String str) {
        if (str == null || str.isEmpty()) return false;

        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    int square(int value) {
        return value * value;
    }
    
    int factorial(int value) {
        int result = 1;

        for (int i = 1; i <= value; i++) {
            result *= i;
        }

        return result;
    }

    void main(String[] args) {
        if (args.length == 0) {
            IO.println("No arguments provided");
            return;
        }

        if (isInteger(args[0])) {
            int value = Integer.parseInt(args[0]);
            IO.println(square(value));
        } 
        else if (!isInteger(args[0]) && args.length == 1) {
            String command = args[0];

            switch (command) {
                case "--help", "-h" -> {
                    // lists the commands
                }
                default -> {
                    IO.println("You should use '--help' or '-h' to see the list of commands.");
                }
            }
        }
        else {
            String command = args[0];
            String operation = args[1];
            int value = Integer.parseInt(args[2]);

            switch (command) {
                case "--operation", "-o" -> {
                    IO.println("Hello operation " + operation);
                }
                case "--directory", "-d" -> {
                    IO.println("Ooooh fancy boy");
                }
                default -> {
                    IO.println("You should use '--help' or '-h' to see the list of commands.");
                }
            }
        }

    }
}

Updated a the code, still having some difficulty. If anyone is able to lend a hand

tepid talon
#

Okay here is a strategy

#
String command = null;

// ... loop through args
// ... if you find -o or --operation
// ...   set command = args[i + 1]

if (command == null) {
    command = <default value>;
}
jaunty niche
#

Ok I think I understand

class CLI {
    boolean isInteger(String str) {
        if (str == null || str.isEmpty()) return false;

        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    int square(int value) {
        return value * value;
    }
    
    int factorial(int value) {
        int result = 1;

        for (int i = 1; i <= value; i++) {
            result *= i;
        }

        return result;
    }

    void main(String[] args) {
        String command = null;
        int value = 0;

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("--operation") || args[i].equals("-o")) {
                command = args[i + 1];
                value = Integer.parseInt(args[i + 2]);
            }
        }


        switch (command) {
            case "square" -> {
                IO.println(square(value));
            }
            case "factorial" -> {
                IO.println(factorial(value));
            }
        }

        if (command == null) {
            IO.println("No arguments provided");
        }
    }
}

Now let me see if I can handle the others here

tepid talon
#
       switch (command) {
            case "square" -> {
                IO.println(square(value));
            }
            case "factorial" -> {
                IO.println(factorial(value));
            }
            case null -> {
                IO.println("No arguments provided");
            }
        }
#

not sure if i introduced this, but this works

jaunty niche
tepid talon
#

what chapter is this?

#

oh goddamn it

#

i put files after it

#

i can just move it back I think

jaunty niche
#

I think a few things I may add as I go through the book would be -

  1. Promoe going through the docs and maybe even a lesson on how to do that.
    a. I can sort of go through the Java Docs with having some experience going through the MDN docs when learning JS, but for a newer individual it may be very overwhelming.
  2. At least in this section while I do enjoy the very like "no hand holding" approach of this challenge, this seems more like a possible project?
tepid talon
#

i dont disagree

#

make some issues so its on my list

jaunty niche
#

Can do

tepid talon
#

this is reminding me how massive this thing is

jaunty niche
#

Haha yea its a BIG book, but honestly I love it, I am not sure just how much in regards to Java I'm exposing myself to by going through it. But I love it, books like this feel like I am going from A - Z at least from the general language understanding sort of way.

Like touching on Data types, Loops, variables, then doing CLI tooling, working with files, etc. All of this stuff is so good to know and I can tell you I am re-learning a lot from a fundamental standpoint as well as leaning the language

#

This is a up to you decision for how broad you want the book to cover but as an example in TOP (The Odin Project) one lesson that is a nice to have is a git lesson. Purely so the individual can learn early on how to work in a terminal doing git commands, like fetch pull rebase commit etc. The only reason I am suggesting it may be useful is because you sort of go into some terminal knowledge but I can also see how that is integrated with working in Java

tepid talon
jaunty niche
tepid talon
#

he's going to charge for it, but i think its going to be a good resource

#

The only reason I am suggesting it may be useful is because you sort of go into some terminal knowledge but I can also see how that is integrated with working in Java
So I agree its useful, but

jaunty niche
#

Issues have been created, as much as I don't want to skip these challenges I may come back once I learn a bit more about how to create files and such.

tepid talon
#

and this is the general restriction I put myself under

tepid talon
#

I dont want to do things without "proper justification"

jaunty niche
tepid talon
#

sure i can

manic plank
jaunty niche
#

Going to have to split this up into a few code blocks due to message limits. But one thing I was curious about in the switch statement in particular it feels kinda "odd" to do an if /else statement while also doing a try/catch lol. Thoughts on this "pattern"?

import java.nio.file.Path;
import java.nio.file.Files;
import java.io.IOException;

class CLI {
    boolean isInteger(String str) {
        if (str == null || str.isEmpty()) return false;

        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    int square(int value) {
        return value * value;
    }
    
    int factorial(int value) {
        int result = 1;

        for (int i = 1; i <= value; i++) {
            result *= i;
        }

        return result;
    }

    void createFile(String path, int value) throws IOException {
        try {
            Path filePath = Path.of(path);
            String content = Integer.toString(value);
            Files.writeString(filePath, content);
        }
        catch (IOException e) {
            throw new IOException("Something appears to have gone wrong");
        }
    }

    void sendHelpMessage() {
        String message = """
        Thanks for using this CLI tool! The list of commands are as follows:
        --operation | -o : This will allow you to perform some operation on a number (square, factorial). The default is to square the value.
        --directory | -d : This will allow you to create a file with the value of an operation. (The default is to square the value)
        --help | -h : Brings you to this help page where all the commands are listed.
        --quit | -q : Will quit the program.
        """;

        IO.println(message);
    }
#
    void main(String[] args) {
        String command = null;
        String path = null;
        int value = 0;

        if (args[0].equals("--help") || args[0].equals("-h")) {
            sendHelpMessage();
            return;
        }

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("--operation") || args[i].equals("-o")) {
                command = args[i + 1];
            }

            if (args[i].equals("--directory") || args[i].equals("-d")) {
                path = args[i + 1];
            }

            else if (isInteger(args[i])) {
                value = Integer.parseInt(args[i]);
            }
        }

        switch (command) {
            case "square" -> {
                int result = square(value);

                if (path != null) {
                    try {
                        createFile(path, result);
                    } catch (IOException e) {
                        IO.println(e.getMessage());
                    }
                } else {
                    IO.println(result);
                }
            }
            case "factorial" -> {
                int result = factorial(value);

                if (path != null) {
                    try {
                        createFile(path, result);
                    } catch (IOException e) {
                        IO.println(e.getMessage());
                    }
                } else {
                    IO.println(result);
                }
            }
            case null -> {
                IO.println("No arguments provided");
            }
            default -> {
                IO.println("We hit a snag, double check your input or use `--help` for more commands");
            }
        }
    }
}