r/badcode • • Nov 13 '20

java Getting Digits using Switch Catch

Post image
881 Upvotes

52 comments sorted by

View all comments

46

u/[deleted] Nov 13 '20 edited Nov 13 '20

The function never returns -1, it just quits! This one does return -1 so that someone could use a while loop to get the digit:

public static int evalDigit(string in, int max) {
    int result = -1;
    try {
        result = String.parseInt(in.trim());
        if (result > max) {
            System.out.println(String.format("The digit entered was too high (max is %d), try again", max));
            result = -1;
        }
        if (result < 0) {
            System.out.println("Negative digits not allowed, try again");
            result = -1;
        }
    }
    catch (NumberFormatException e) {
            System.out.println("Invalid digit was entered, try again");
    }
    return result;
}

25

u/HolySpecs Nov 13 '20

I just declared result as -1 because I didn't want the program to pass something if the data entered wasn't valid. Also, I wasn't allowed to use loops of any kind so yay more pain for me. It was an exercise to practice using recursive functions.

0

u/[deleted] Nov 13 '20

[deleted]

10

u/HolySpecs Nov 13 '20

No it was in a separate part, sorry for the potential misinformation.

7

u/DesiresQuiet Nov 13 '20

What loop?

2

u/HolySpecs Nov 13 '20

One of the conditions I was given was that I couldn't use for loops, while loops or do while loops for the entirety of the code

3

u/DesiresQuiet Nov 13 '20

Yeah, so what loop?

1

u/halfanothersdozen Nov 14 '20

You can't use loops, huh?

Why?

I swear these classes don't prepare to code in the real world.

3

u/AutoModerator Nov 13 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/lovegro, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/LifeHasLeft Nov 13 '20

That was my first thought. Exiting this way hasn’t seemed like a good idea to me since maybe when I was in my first classes. But I could argue proper error handling is a skill in and of itself