Skip to content
Advertisement

Substring not equal to the string of the first character

I am struggling to figure out what’s wrong with my code. When the user input is “apple” I get that it doesn’t begin with a vowel.

import java.util.*;
public class StringeExerciseElearn {
    public static void main(String[] args) {
        Scanner k = new Scanner(System.in);
        System.out.println("Type a word: ");
        String input = k.next();
        String l = input.substring(0);
        String a = "a";
        String e = "e";
        String i = "i";
        String o = "o";
        String u = "u";

        if(l.equals(a) || l.equals(e) || l.equals(i) || l.equals(o) || l.equals(u))
            System.out.println(input + " begins with a vowel!");
        else
            System.out.println(input + " doesn't begin with a vowel");
        }
    }
}

Advertisement

Answer

You made a mistake using the substring method, you should say the start position in first parameter and the end position in second parameter :

String l = input.substring(0, 1);

And now it works fine 🙂 :

Type a word: 
apple
apple begins with a vowel!
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement