Java if语句数据输入限制

时间:2015-10-30 20:33:07

标签: java string indexof

我试图了解.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);
    }

}

3 个答案:

答案 0 :(得分:4)

indexOf返回调用它的字符串中给定字符串的索引。您无法将此返回值分配给String - 必须将其分配给int

int index = stringwords.indexOf("a");

答案 1 :(得分:3)

因为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);
    }

答案 2 :(得分:3)

indexOf返回一个String。查看JavaDoc:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)

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);
    }

}