Detecting last character

Tags: , ,



Im trying to detect whether the last character of a string contains an operator using an array checker that was previously used for integers. For some reason the code will always display “Not In” Even if the last character is an operator

class Main {
    public static boolean useLoopString(String[] arr, String targetValue) 
    {
        for (String s : arr) {
            if (s == targetValue)
                return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String[] op={"+","-","×","÷"};
        String eq = "43+4+";
        String eqLast=eq.substring(eq.length()-1);
        System.out.println(eqLast);
        boolean in=useLoopString(op,eqLast);
        if(in){
            System.out.println("In");
        }
        else{
            System.out.println("Not In");
        }
    }
}

Answer

You can use char to compare, like this:

  public static boolean useLoopString(char[] arr, char targetValue) {
        for (char ch : arr) {
            if (ch == targetValue)
                return true;
        }
        return false;
    }

    public static void main(String[] args) {
        char[] op = { '+', '-', '×', '÷' };
        String eq = "43+4+";
        char eqLast = eq.charAt(eq.length() - 1);
        boolean in = useLoopString(op, eqLast);
        if (in) {
            System.out.println("In");
        } else {
            System.out.println("Not In");
        }
    }


Source: stackoverflow