简体   繁体   中英

How to find the last character in a String?

There is a huge array of Strings and i have to loop through the array of strings see which words has a certain length ( qualifyingLenght ) and it should be ends with the char a for Task 3 .

I tried really hard and couldn't figure it out. TIA.

package set07110;
/**
 * A String array defined as a static instance variable called data;
 */
public static String[] data = { "Achelous", "Ares", "Clytemnestra", "Eurystheus", "Icarus", "Naiads", "Phlegethon", "Sterope",
        "Acheron", "Argo", "Cocytus", "Euterpe", "Io", "Napaeae", "Phosphor", "Stheno", "Achilles", "Argus", };



public static void main(String[] args) { //Print the only two character name


    System.out.println("Task 1");
    System.out.println("Enter Length: ");
    Scanner scan = new Scanner(System.in);
    int qualifyingLength = scan.nextInt();

    for(String string: data) {

        if(!(qualifyingLength == string.length())) {
            System.out.println("Try again");
        }
        else if (qualifyingLength == string.length()) {
            System.out.println("The words are: " + string);
        }
    }
    System.out.println("Task 2");
    int count = 0; //Identify the three characters where the name ends with "seus"
    for (int index = 0; index < data.length; index++) { {
        if (data[index].contains("seus")) {
            count++;
            boolean seus = data[index].contains("seus");
            System.out.println("The words containing seus: " + data[index]);
        }

    }


    }
    //Print the names with 9 letter that end in "a".
    System.out.println("Task 3");
    System.out.println("Enter Length: ");
    int qualifyingLength1 = scan.nextInt();  // enter a number which indicates how much letter
    // do we want in a word
    for(String string: data) {
        int lastChar = (data.length - 1);
        boolean startsWithA = data.charAt(lastChar) == 'a'; //(have to find the last character in a Array of Strings
        // and see if the word ends with the character "a" --> (doesn't work)
        if(qualifyingLength1 == string.length() ) {
            System.out.println("The words are: " + string);
        }

    }
}

First check the length before and use simply endsWith as

for(String string: data) {
    if(qualifyingLength1 == string.length() && string.endsWith("a") )      
       // got your input
    // else {continue;} //optional
}

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