-3

I have been asked to prompt the user for a string data and then validate the user input against an array of the data containing the values that the user should enter and prompt the user is the string is not valid.

 public static void main(String[] args)
 {
 Scanner keyboard = new Scanner(System.in);
 //List of values the user suppose to enter
 String[] list = {"Monday","Thusday", "Wednesday", "Thusday", 
 "Friday", "Saturday", "Sunday"}
 System.out.println("Enter a day:"\n Eg: Monday or Thursday")
 String day = keyboard.next();
 /**
 What should I write so that I can validate the user input against an
 string array of days? And prompt the user again if his input is not 
 a day.
 */
}
asked Jan 20, 2018 at 22:03
2

2 Answers 2

0

This should work

public static void main(String[] args)
{
 Scanner keyboard = new Scanner(System.in);
 //List of values the user suppose to enter
 String[] list = {"Monday","Thusday", "Wednesday", "Thusday", 
 "Friday", "Saturday", "Sunday"};
 System.out.println("Enter a day:");
 String day = keyboard.next();
 if(!Arrays.asList(list).contains(day)) {
 System.out.println("Input is not a day!");
 }
}
answered Jan 20, 2018 at 22:21
0

You can loop through the Array using a for loop (or a do/while loop, or a while loop) then compare the User's input with that which is contained within each array element to see if there is a match.

You can even take it to a point where.... What if the User enters monday instead of Monday? Or what if the user enters mon or Mon instead of Monday? You can handle these situations (if desired) during the looping of the Array (within a for loop code block for example).

In the case of where a User enters monday instead of Monday, read how to utilize Java's String.toLowerCase(), String.toUppercase(), and or the String.equalsIgnoreCase() methods.

In the case of where a User enters Mon instead of Monday, read how to utilize Java's String.length() and String.substring() methods.

You could of course have these particular situations contained within your String Array for example:

{mon, Mon, monday, Monday, MONDAY, tue, Tue, tuesday, Tuesday, TUESDAY, ...etc...}

but then, that's no fun and is more prone to errors (tUesDay). You never know how a User will enter a string, even if you provide an example but then again you can simply refuse to accept their input unless they follow the rules!

answered Jan 20, 2018 at 23:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.