简体   繁体   中英

How do I validate string within an array to a method in java

How do I verify the input of the user to match the array in the call method, so that it will return the letter and show it along with validated it as a string?

String[] options1 = { "a", "b", "c" };  
choice = getValidString(sIn, "Please enter 'a', 'b' or 'c': ",
             "Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.",
             options1); // call method
System.out.printf("The letter your entered was: %s\n\n", choice);

public static String getValidString(Scanner sIn, String question,
                                    String warning, String[] choices)
    String input = "";
    boolean valid= false;
    do {
        System.out.println(question);
        input = sIn.nextLine();
        try {
            Arrays.asList(choices).contains(input); // this is where the problem resides.
            valid = true;
        } catch(Exception e) {
        System.out.println(warning); } 
    } while (!valid);
    return input ;
}

Desired output:

Please enter 'a', 'b' or 'c': hypotenuse.
Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.
Please enter 'a', 'b' or 'c': b
The letter your entered was: b

A Java array does not have any method like contains . Convert the array into a List using Arrays.asList and then you can apply contains on the resulting List .

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sIn = new Scanner(System.in);
        String[] options1 = { "a", "b", "c" };
        String choice = getValidString(sIn, "Please enter 'a', 'b' or 'c': ",
                "Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.", options1); // call mehtod
        System.out.printf("The letter your entered was: %s\n\n", choice);
    }

    public static String getValidString(Scanner sIn, String question, String warning, String[] choices) {

        String input = "";
        boolean valid = false;
        List<String> choiceList = Arrays.asList(choices);
        do {
            System.out.println(question);
            input = sIn.nextLine();
            try {
                valid = choiceList.contains(input);
                valid = true;
            } catch (Exception e) {
                System.out.println(warning);
            }
        } while (!valid);
        return input;
    }
}

A sample run:

Please enter 'a', 'b' or 'c': 
b
The letter your entered was: b

Feel free to comment in case of any doubt/issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM