rhondaoj
rhondaoj

Reputation: 1

How to access a specific character in a String ArrayList

I am trying to print out the words in the ArrayList, given they do not start with an "S". So, I need the first index of each item in the String ArrayList

My first attempt was the condition in the if statement to be: if(itemsArrayList.charAt(0) == "S") but that throws me an error.

This one doesn't throw me an error, but it still prints out all of the items in the ArrayList (not skipping over "Slim" and "Shady")

code

//won't let me post code as a text

Upvotes: -3

Views: 60

Answers (2)

Kurojin
Kurojin

Reputation: 310

First, you had an error in itemsArrayList.charAt(0) == "S" because you were comparing a string reference to a char primitive (different types).

Second, you still print all the strings because your condition is never true, you are testing if the first element of your string list (itemsArrayList.get(0)) starts with S which is never the case, because you first element is hello.

you test should look like this

if(x.charAt(0) == 'S')

notice how 'S' is a character and not a String due to simple quotes

Upvotes: 0

Jorge Vera
Jorge Vera

Reputation: 21

See this please for Java

import java.util.ArrayList;
public class MyClass {
    public static void main(String args[]) {
        ArrayList<String> cars = new ArrayList<String>();
        cars.add("Volvo"); //position 0 in the array
        cars.add("BMW"); //position 1 in the array
        cars.add("Ford"); //position 2 in the array
        cars.add("Mazda"); //position 3 in the array
        System.out.println(cars.get(0).toString().charAt(0));
        System.out.println(cars.get(1).toString().charAt(0));
        System.out.println(cars.get(2).toString().charAt(0));
        System.out.println(cars.get(3).toString().charAt(0));
    }
}

Upvotes: 0

Related Questions