4

Hello here is some code to check for a valid character, although the code is not working. Even if 'operand' is a valid character it will never print yes, and return false. No matter what even if the character is valid it just doesn't recognize it and always goes to the else statement. Please help!

public static boolean checkValidOperands(char operand) {

    char[] validOperators = {'+', '-', '*', '/', 'q'};
    List<char[]> validOp = Arrays.asList(validOperators);
    if (validOp.contains(operand))  {
        System.out.println("Yes");
        return false;
    }  else {
        System.out.println("Please enter valid operand");
        return true;
    }
}
Nearpoint
  • 7,202
  • 13
  • 46
  • 74

3 Answers3

7

You could use:

List<Character> validOp = Arrays.asList('+', '-', '*', '/', 'q');
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

The way you are creating a list of characters is wrong.

In your current code the list that you made is actually a list of character arrays, instead of characters.

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

public class Test{
    public static void main(String[] args){
    char ch = '+';
    System.out.println(checkValidOperands(ch));

    }

    public static boolean checkValidOperands(char operand) {

        Character[] validOperators = {'+', '-', '*', '/', 'q'};
        List<Character> validOp = Arrays.asList(validOperators);
        if (validOp.contains(operand))  {
            System.out.println("Yes");
            return false;
        }  else {
            System.out.println("Please enter valid operand");
            return true;
        }
    }
}

PS: Also for future, do not use List<char>, List<int> etc.. as you cannot use a primitive type for generic in Java. Use their corresponding Object counter parts instead. Refer to this question for more information Why can Java Collections not directly store Primitives types?

Community
  • 1
  • 1
Ankit
  • 6,772
  • 11
  • 48
  • 84
0

A string is a better data structure for a set of characters. For example,

String validOperators = "+-*/q";

if (validOperators.indexOf(operand) != -1)  {
    System.out.println("Yes");
    return false;
}
John Henckel
  • 10,274
  • 3
  • 79
  • 79