简体   繁体   中英

Why is the 'contains' not working? or I am doing it wrong?

Objectives:

  1. Check if the user input is a letter
  2. Check if it is a vowel or consonants
  3. Check if there's a duplicate letter in a String

Contains not returning anything or I am using it wrong

Scanner out = new Scanner(System.in);
    System.out.print("Please insert a text: ");

    String[] vowels = {"a", "e", "i", "o", "u"}; 
    String userInput = out.nextLine();
    char[] charUserInput = userInput.toCharArray();
    String temp = "";
    String temp1 = "";
    for (int i = 0; i <= charUserInput.length -1; i++){
        if (Character.isLetter(charUserInput[i])){
            if (Character.toString(charUserInput[i]).equalsIgnoreCase(vowels[0]) || (Character.toString(charUserInput[i]).equalsIgnoreCase(vowels[1]) ||
                    (Character.toString(charUserInput[i]).equalsIgnoreCase(vowels[2]) || (Character.toString(charUserInput[i]).equalsIgnoreCase(vowels[3]) || 
                            (Character.toString(charUserInput[i]).equalsIgnoreCase(vowels[4])))))){
                    if (!Character.toString(charUserInput[i]).contains(temp)){
                        temp += Character.toString(charUserInput[i]);
                    }
            }else{
                if (!Character.toString(charUserInput[i]).contains(temp1)){
                    temp1 += Character.toString(charUserInput[i]);
                }

            }
        }
    }
    System.out.println(temp);
    System.out.println(temp1);
    out.close();

Looks like you inverted conditions: use

temp.contains(Character.toString(charUserInput[i])) 

instead of

Character.toString(charUserInput[i]).contains(temp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM