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