我如何制作一个Java程序来检查字符串中是否有元音?

时间:2018-10-21 03:27:05

标签: java arrays

我制作了一个程序来检查字符串,如果字符串中至少有一个元音。但是,当我输入一个带有元音的字符串时,结果是“您的密码字不可接受”,而不是“您的密码字可接受”。

有人可以告诉我我做错了什么吗?谢谢!

这是程序:

import java.util.Scanner;
public class checker {
    static Scanner input= new Scanner(System.in);
    public static void main(String[] args) {
        String password;
        System.out.println("enter your password:");
        password= input.next();
        String vowel[]= {"a","e","i","o","u"};
        for(int i=0; i<5;i++) {
            boolean check[] = new boolean[5];
            check[i]=password.contains(vowel[i]);
             if(i==vowel.length-1&&check[0] ==false && check[1]==false && check[2]==false && check[3]==false && check[4]==false) {
                System.out.println("your password word is not acceptable");
             }else System.out.println("your password is acceptable");
          }
      }
 }

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式进行操作:

import java.util.Scanner;
public class checker {
    static Scanner input= new Scanner(System.in);
    public static void main(String[] args) {
        String password;
        System.out.println("enter your password:");
        password= input.next();
        String vowel[]= {"a","e","i","o","u"};
        boolean check = false;
        for(int i=0; i<5;i++) {
            check = password.toLowercase().contains(vowel[i]);
            if(check){ 
                break; 
            }
       }
             if(!check){
                System.out.println("your password word is not acceptable");
             }else {
                System.out.println("your password is acceptable");
             }
      }
 }

答案 1 :(得分:1)

您可以使用正则表达式轻松检查字符串是否包含元音。请检查以下代码:

public static void main(String[] args) {
    String input = "tssta";
    String regex= ".*[AEIOUaeiou].*";
    if(input.matches(regex)){
        System.out.println("your password word is acceptable");
    }else {
        System.out.println("your password word is not acceptable");
    }
}