Vanessa Reda
Vanessa Reda

Reputation: 1

Looping without a loop?

I was hoping someone might be able to take a look at this for me. I've just started with Java and this is my first project, but it's got a weird bug I can't seem to figure out.

The method is just supposed to return true or false depending on what the user enters. It does work, the only thing is that is asks the user twice. It takes the input but then asks again and does the evaluation on the second input. I'm not sure what to call it, but if anyone can tell what's going on I would really appreciate it!

public static boolean yesOrNo(){
    System.out.print("Would you like to roll again? Type 'y' for yes or 'n' for no: ");
    char c = screen.next().trim().charAt(0);
    if (c == 'y' || c == 'Y' || c == 'n' || c == 'N') { 
        switch (c) {
        case 'y': return (true);
        case 'Y': return (true);
        case 'n': return (false);
        case 'N': return (false);
        }
    }
    else {
        System.out.println("Invalid input, try again!!");
        yesOrNo();
    }
    return (true);
}

edit: The input for the scanner is

public static Scanner screen = new Scanner(System.in);

which I have at the top of the program just inside the class. It doesn't seem to be giving me problems in any of the other input situations. It doesn't print anything else but ask for the input twice, even though I can put a print statement in a see that it gets the character the first time. I also tried changing the call for the function in itself to

return(yesOrNo());

but no luck. Would there be any way to call the function again without recursion?

Upvotes: 0

Views: 449

Answers (3)

qdo
qdo

Reputation: 92

You can use while loop rather than using recursion here.

public static boolean yesOrNo(){
    boolean run = true;

    while(run){
        System.out.print("Would you like to roll again? Type 'y' for yes or 'n' for no: ");
        char c = screen.next().trim().charAt(0);

        if (c == 'y' || c == 'Y' || c == 'n' || c == 'N') { 
            switch (c) {
                case 'y': return true;
                case 'Y': return true;
                case 'n': return false;
                case 'N': return false;   
            }
            run = false;
        }
        else {
            System.out.println("Invalid input, try again!!");
        }
    }
    return true;
}

Upvotes: 0

Ash
Ash

Reputation: 2602

Ok, what you are doing on the else where you call yesOrNo() from inside yesOrNo() is recursion.

To fix you need to return the answer from the next call;

else {
    System.out.println("Invalid input, try again!!");
    return yesOrNo();
}

Upvotes: 5

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

in your else you are calling the method again.

     else {
    System.out.println("Invalid input, try again!!");
    yesOrNo();
      }

Upvotes: 1

Related Questions