Array doesn't change after running this code. What is the reason of it? Thank you
Scanner s = new Scanner(System.in);
String [] h = new String[100];
int hlds = 0;
while (true) {
System.out.print("Enter: ");
if(s.hasNextLine()) {
String str = s.nextLine();
if (Pattern.matches("[abc]", str)) {
h[hlds++] = str;
}
for( int i = 0; i < h.length ; i++){
System.out.println(h[i]);
}
break;
}
4 Answers 4
Pattern.matches("[abc]", str)
Evaluates to true only if you enter either a or b or c
because of the regex you have used [abc], see the docs about regular expressions
If you enter ab then it would not be accepted.
If you want your input to contain any of the char then you could change your regex to [abc]+.
Comments
Your regex [abc] means "a single character either a, b or c".
Change your regex to [abc]+, meaning "one or more characters either a, b or c"
Comments
Extra Info:
This would also work:
str.matches("[abc]+");
It calls Pattern.matches(regex,this); internally. (where regex is the regular expression used)
Comments
(updated after reading all comments...)
Okey, so if I understand it right: You want to store into the array from input line those who contains a, b or c letters.
apple, ball, catch, table, tictac... will be stored. Right?
I would use the String contains, or indexof to fins a, b, and c letters. This is more efficient that regex.
Scanner s = new Scanner(System.in);
String [] h = new String[10];
Pattern p = Pattern.compile("(a|b|c)");
for(int hlds=0; hlds<h.length;hlds++ ) {
System.out.print("Enter: ");
String str = s.nextLine();
/* with regex
if( p.matcher(str).find() ) {
h[hlds] = str;
}
*/
/* with contains */
if( str.contains("a") || str.contains("b") || str.contains("c") ) {
h[hlds] = str;
}
}
System.out.println(Arrays.toString(h));
if (Pattern.matches("[abc]", str))is never met.