简体   繁体   English

为字符串编写charAt方法

[英]Write charAt method for string

`Having problems in the if statement. `if语句中有问题。 It kept on giving me Error: incomparable types: java.lang.String and int. 它一直在给我错误:无法比较的类型:java.lang.String和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. list [i]是一个字符串,而index是一个int。

Probably you want 可能你想要

if(i==index) it seems if(i==index)似乎

You don't need the for loop at all: simply return list[index] as your result. 您根本不需要for循环:只需将list[index]作为结果返回即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM