简体   繁体   中英

Write charAt method for string

`Having problems in the if statement. It kept on giving me Error: incomparable types: java.lang.String and int. How do I go about this?

String str = "helloworld"; // At main method of my program

public static String charAt(int index) {
    String result = "";
    int lol;
    String[] list = str.split("");
    for(int i = 0; i < list.length; i++) {
      if(list[i] == index) {
        result += list[i];
      }
    }
    return result;
}

You have a pretty clear error message.

if(list[i] == index)

You cannot do that since both are not comparable. list[i] is a string and index is an int.

Probably you want

if(i==index) it seems

You don't need the for loop at all: simply return list[index] as your result.

String[] list = str.split("");
if (list.length > index) {
    return list[index];
}
throw new IndexOutOfBoundsException();

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