Search code examples
javaloopsconditional-operatorcontrol-flow

Redirecting the flow of the code for an Error Message


I want to redirect the flow of code to "1" part after the else statement.

I have tried to achieve it by creating loops and different methods but I couldn't make it.

The thing that I want is, it will give an error when an invalid answer is given and will ask the questions again.

import java.util.Scanner;

public class OddsAndEvens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Let’s play a game called “Odds and Evens”");
        System.out.println("What is your name?");
        String name = input.next();

        // 1 <------------------------

        System.out.println("Hello " + name + " which one do you choose? (O)dds or (E)vens?"); 

        String oe = input.next();

        if (oe.equalsIgnoreCase("e")) {
            System.out.println(name + " has picked evens! The computer will be odds.");
        }
        if (oe.equalsIgnoreCase("o")) {
            System.out.println(name + " has picked odds! The computer will be evens.");
        }

        else {
            System.out.println("You have typed an invalid answer.");

        }


    }

}

Solution

  • The fix is simple, see below

        import java.util.Scanner;
    
        public class OddsAndEvens {
            public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                System.out.println("Let’s play a game called “Odds and Evens”");
                System.out.println("What is your name?");
                String name = input.next();
                while(true) {
                // 1 <------------------------
    
                System.out.println("Hello " + name + " which one do you choose? (O)dds or (E)vens?"); 
    
                String oe = input.next();
    
                if (oe.equalsIgnoreCase("e")) {
                    System.out.println(name + " has picked evens! The computer will be odds.");
                    //do even logic here
                    break;
                }
                if (oe.equalsIgnoreCase("o")) {
                    System.out.println(name + " has picked odds! The computer will be evens.");
                    //do odd logic here
                    break;
                }
    
                else {
                    System.out.println("You have typed an invalid answer, lets try again");
    
                }
            }
    
    
            }
    
        }