Repeat process upon receiving invalid entry

Asked

Viewed 23 times

-2

I am unable to make this program repeat after the user has put an invalid answer.

If he/she type a response does not validate how it could be done for the program to run again to be put the response as requested?

import java.util.Scanner;

public class InputValidationString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner in= new Scanner(System.in);
        
        
        System.out.println(" Do you like to code?:");
        String liketocode=in.nextLine();
        
        
        if (liketocode.equalsIgnoreCase("Y")) {
            System.out.println("That's great! I do too!");
        } if (liketocode.equalsIgnoreCase("N")) { 
            System.out.println("That's ok. There are many other wonderful things in life to learn.");
        } else { System.out.println("Invalid Response! Please answer with a 'Y' or 'N'.");
        
        } while (liketocode.equalsIgnoreCase("Y")||(liketocode.equalsIgnoreCase("N")));
    
        in.close();
        
        // Author : Messias Kennedy             
    } // the end of main 
} // the end of public class

1 answer

1

The problem is that your code is poorly structured. First the condition of the while seems reversed if your intention is to repeat something while the entry is invalid. Second, while does nothing, the semicolon at the end of it should be a block of code to be repeated or else you would have used a block do before the while (as is done in the example).

A possible solution would be:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        
        String liketocode;
        boolean respostaValida;
        do
        {
            System.out.println("Do you like to code?:");
            liketocode = in.nextLine();
            
            respostaValida = respostaÉValida(liketocode);
            if (!respostaValida) {
                System.out.println("Invalid Response! Please answer with a 'Y' or 'N'.");
            }
        }
        while (!respostaValida);

        if (liketocode.equalsIgnoreCase("Y"))
            System.out.println("That's great! I do too!");
        else if (liketocode.equalsIgnoreCase("N"))
            System.out.println("That's ok. There are many other wonderful things in life to learn.");        
    
        in.close();           
    }

    private static boolean respostaÉValida(String resposta)
    {
        return resposta.equalsIgnoreCase("Y") || resposta.equalsIgnoreCase("N");
    }
} 

See working on Repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.