Home > OS >  User has to enter a letter and if the letter is found at the array then it should print "is a v
User has to enter a letter and if the letter is found at the array then it should print "is a v

Time:11-10

I have an array of the vowels in the alphabet and the user should enter a letter. This letter has to be checked if its in the array of vowels or not If it is found in the array of vowels then print letter is a vowel else print letter is a constant.

My problem is that

when I enter a letter it tests this letter 5 times (the size of the array) until it finds it and prints letter is a vowel but it also prints 4 times letter is a constant because it goes through the array letter by letter. Check the code:

    public static void main(String[] args){
    Scanner g = new Scanner(System.in);
    char[] Vowels = {'A','I','O','U','E'};
    System.out.println("Enter a letter: ");
    char L = g.next().charAt(0);
for(int i = 0;i<Vowels.length;i  ){
    if(L==Vowels[i]){
        System.out.println(L " is a vowel");
        break;
    }
    else
    System.out.println(L " is a constant");
}
    }
}

CodePudding user response:

first of all: we usually dont capitalize variable names, but that aint no problem rn. There are a few approaches to solve this question: i would create a bool. Take a look at the code:

public static void main(String[] args){
        Scanner g = new Scanner(System.in);
        char[] Vowels = {'A','I','O','U','E'};
        System.out.println("Enter a letter: ");
        char L = g.next().charAt(0);
        boolean isVowel = false;
        for(int i = 0;i<Vowels.length;i  ){
            if(L==Vowels[i]){
                System.out.println(L " is a vowel");
                isVowel = true;
                break;
            }

        }
        if (!isVowel) {
            System.out.println(L " is a constant");
        }
    }

CodePudding user response:

Here's a version of your code that does what you want. Note that the print statement for a consonant has been moved out of the loop. I also changed the variable names to use correct case, and I made a minor tweak to allow the code to work with both uppercase and lowercase input. I also moved the line that prints the prompt for input. I assume you want that to print before the user is expected to enter a letter.

public static void main(String[] args){
    System.out.println("Enter a letter: ");
    Scanner g = new Scanner(System.in);
    char[] vowels = {'A','I','O','U','E'};
    char l = g.next().toUpperCase(Locale.ROOT).charAt(0);
    int i;
    for (i = 0;i<vowels.length;i  ) {
        if (l == vowels[i]) {
            System.out.println(l   " is a vowel");
            break;
        }
    }
    if (i == vowels.length)
        System.out.println(l   " is a constant");
}
  • Related