Java checking if string contains certain letters with a certain range with contains or equals method

4.3k views Asked by At
import.java.util.Scanner;

public class Test{
   public static void main(String[] args){
   Scanner sc = new Scanner(System.in)
   String operation = sc.nextLine();
   }
}

When I want to see, if the string operation contains certain letters, I could write f.ex.

    if(operation.contains("a") || operation.contains("b")){
        System.out.println("This is not a valid choice. Please retry!");
    }

But I want to know what to write, if the string contains letters, e.g. from a to k. If I write it with || every single time, it's not efficient. EDIT: I'm only allowed to use the methods contains and equals.

2

There are 2 answers

4
Roman Puchkovskiy On BEST ANSWER

Try using a regex:

if (operation.matches(".*[a-k].*") {
    ...
}

An alternative:

boolean contains = false;
for (char charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
    if (operation.indexOf(charToCheck) >= 0) {
        // found something
        contains = true;
        break;
    }
}

A later update

Oh, indexOf() is not allowed too. A version which uses nested loops:

boolean found = false;
for (char ch : operation.toCharArray()) {
    for (ch charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
        if (ch == charToCheck) {
            found = true;
            break;
        }
    }
    if (found) {
        break;
    }
}
0
Lothar On
char[] chars = operation.toCharArray();
for (int i = 0; i < chars.length; i++) {
    char val = chars[i];
    switch(val) {
        case a:
        case b:
        case c:
        case d:
        case e:
        case f:
        case g:
        case h:
        case i:
        case j:
        case k:
            System.out.println("This is not a valid choice. Please retry!");
            break;
     }
}