Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java if语句数据输入限制_Java_String_Indexof - Fatal编程技术网

Java if语句数据输入限制

Java if语句数据输入限制,java,string,indexof,Java,String,Indexof,在阅读了.indexOf()之后,我试图了解它的工作原理。我创建了一个随机字符串并尝试搜索字符a 然而,在尝试了一些事情之后,我得到了这个错误,尽管我总是在所有阶段声明String: 不兼容类型:int无法转换为java.lang.String 万分感谢所有能够帮助我了解我的错误所在或提出正确方法的人 public class sad { // instance variables - replace the example below with your own private

在阅读了
.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);
    }

}
返回所调用字符串中给定字符串的索引。不能将此返回值分配给
字符串
-必须将其分配给
int

int index = stringwords.indexOf("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);
    }

indexOf返回一个字符串。看看JavaDoc:


indexOf
返回一个
int
而不是
String
do
int a=stringwords.indexOf(“a”)
构造函数也应该是
public sad()
,不带空格。请遵守Java编码约定:类型名称(类、接口、枚举)应该以大写字母开头(例如
BigPicture
)。方法、变量和字段名称应以小写字母开头(例如,
bigPicture
),常量应全部大写(例如,
BIG\u PICTURE
)。字符串返回中的indexof方法可能更有意义。干得好,伙计们。更改
构造函数
:p更改
构造函数
:P@3kings我对它进行了编辑,但无论哪种方式都有效。谢谢你的改进。
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);
    }

}