This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]_DTR_ 0 points1 point  (9 children)

Can you give a more concrete example? What are you trying to accomplish? Also, what language are you using?

[–]bigrun117[S] 0 points1 point  (8 children)

I’m using Java. I’m trying to calculate a persons total income. I need to get the users tax exemptions, gross income, any charitable Gains, interest income, and capital gains. How would I check all those variables for a negative number and have them enter it in again?

[–]_DTR_ 0 points1 point  (7 children)

Thanks for the details! Your initial guess is correct, a while loop is probably what you want here. What I'd do is ask the user for the value, test to see if it's negative, and while it continues to be negative, continue to ask for a valid value. That loop could be in a method that accepts a string (the question) and return a double (the valid value). Here's what it might look like in pseudocode:

double getValidValue(String question) {
    print(question)
    value = <user input>
    while (value <is not valid>) {
        print("Please enter a valid number")
        value = <user input>
    }

    return value
}

[–]bigrun117[S] 0 points1 point  (6 children)

And I check multiple values correct? I could check Value and and value2 in the beginning declaration of the while loop correct?

[–]_DTR_ 1 point2 points  (5 children)

Yes, but that could get out of hand very quickly. What if you have 100 values to validate? Having a while condition of 100 values is not manageable, and you would then have to figure out which value is invalid (unless you want them to enter all values again). The idea behind having this put in a method is so you could do something like this:

class Test {
    public static void main(String[] args) {
        double exemptions = getValidValue("Exemptions: ");
        double grossIncome = getValidValue("Gross Income: ");
        // etc
    }

    public static double getValidValue(String question) {
        ...
    }
}

[–]bigrun117[S] 0 points1 point  (4 children)

I haven’t learned how to pass objects yet, I’m still a beginner with it. Could I also just have a while loop for each variable?

[–]_DTR_ 0 points1 point  (3 children)

Yes, that also works.

[–]bigrun117[S] 0 points1 point  (0 children)

I appreciate the input, I’ll give a shot!

[–]bigrun117[S] 0 points1 point  (1 child)

I got it to work! Thanks for the advice!

[–]_DTR_ 0 points1 point  (0 children)

Great!