在阅读了有关.indexOf()的内容后,我想尝试一下。我创建了一个随机字符串,并尝试搜索字符a

但是,尽管尝试了所有步骤,但在所有阶段都总是声明String,但仍然遇到此错误:

不兼容的类型:int无法转换为java.lang.String

一百万感谢所有可以帮助我了解我要去哪里或提出正确方法的人。

public class sad
{
    // instance variables - replace the example below with your own
    private String stringwords;

    /**
     * Constructor for objects of class sad
     */
    public void sad()
    {
        stringwords = "this is some words a cat";
    }

    //
    public void search()
    {
      String a = stringwords.indexOf("a");
           System.out.println(a);
    }

}

最佳答案

因为stringwords.indexOf("a");是整数。您只是在问字母a出现在什么位置,它给出了数字位置。

例如:

String test = "Hello";
int a = test.indexOf("e");
//a = 1. First letter has the value 0, the next one 1 and so forth.

做这个:
public class sad
{
    // instance variables - replace the example below with your own
    private String stringwords;

    /**
     * Constructor for objects of class sad
     */
    public sad()
    {
        stringwords = "this is some words a cat";
    }

    //
    public void search()
    {
      int a = stringwords.indexOf("a");
           System.out.println(a);
    }

09-18 02:27