Checking if an array has a specific character, why is my code not working?

Hello, here is some code to check for a valid character, although the code does not work. Even if the operand is a valid character, it will never print β€œyes” and will not return false. Regardless of the fact that, even if the character is valid, it simply does not recognize it and always moves on to the else expression. 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; } } 
+4
source share
3 answers

You can use:

 List<Character> validOp = Arrays.asList('+', '-', '*', '/', 'q'); 
+7
source

The way you create a list of characters is wrong.

In your current code, the list you created is actually a list of arrays of characters, not 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 in the future, do not use List<char> , List<int> , etc., since you cannot use a primitive type for the general in Java. Instead, use the corresponding counter elements. See this question for more information. Why can't Java collections directly store primitive types?

+2
source

A string is the best data structure for a character set. For instance,

 String validOperators = "+-*/q"; if (validOperators.indexOf(operand) != -1) { System.out.println("Yes"); return false; } 
0
source

All Articles