Java:字符串索引超出范围:-1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10818232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: String index out of range: -1
提问by gossfunkel
New code:
新代码:
I have no idea what's going on here, I'm getting this error:
我不知道这里发生了什么,我收到此错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1949)
at client0_0_2.loginToClient(client0_0_2.java:98)
at client0_0_2.general(client0_0_2.java:196)
at client0_0_2.<init>(client0_0_2.java:208)
at client0_0_2.main(client0_0_2.java:215)
and this is the contents of the method that's causing the error:
这是导致错误的方法的内容:
public String loginToClient() throws FileNotFoundException, IOException {
//decryptUsers();
int tries;
tries = 5;
while (tries > 0) {
System.out.println("LOGIN");
String usnm = c.readLine("Username: ");
char [] passwd = c.readPassword("Password: ");
users = new FileInputStream("users.fra");
DataInputStream dis = new DataInputStream(users);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String logindat = br.readLine();
System.out.println(logindat);
int startUsnm = logindat.indexOf(usnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
if (startUsnm == -1) {
System.err.println("Username not recognised, please try another or create user.");
usnm = "INV";
return usnm;
}
else {
int tendUsnm = logdat.indexOf(':');
int startPass = endUsnm + 1;
int tendPass = logdat.indexOf('.');
String Usnm = logdat.substring("0", tendUsnm);
String Pass = logdat.substring(startPass, endPass);
char [] Passwd = Pass.toCharArray();
if (usnm.equals(Usnm)) {
if (Arrays.equals(passwd,Passwd)) {
System.out.println ("Logged in. Welcome, " + usnm + ".");
String data = "LOGIN: " + usnm;
printLog(data);
//encryptUsers();
return usnm;
}
else {
System.out.println ("Incorrect password, please try again.");
String data = "PASWFAIL: " + usnm;
printLog(data);
tries -= 1;
}
}
else {
System.out.println ("Username not recognised.");
printLog("USNAMFAIL");
usnm = "INV";
return usnm;
//encrytUsers();
}
}
}
//encryptUsers();
System.exit(2);
return usnm;
}
It looks kinda like it's trying to access the last character of something and that's upsetting it, but I have no idea why. Any help for a total newbie?
看起来有点像它试图访问某个东西的最后一个字符,这让它感到不安,但我不知道为什么。对新手有什么帮助吗?
edits:
编辑:
users.fra
contains username:password
at the time of execution.
users.fra
包含username:password
在执行时。
note: line 98 is the
注意:第 98 行是
char [] Passwd = Pass.toCharArray();
n.b. not homework, a personal project.
nb 不是作业,是个人项目。
Will add in a method to deal with the event that username is not in users.fra
.
将添加一个方法来处理用户名不在的事件users.fra
。
回答by unholysampler
indexOf()
returns -1 when the argument can't be found. I bet that the string you are searching does not have one of the characters you are searching for and it is causing an invalid index when you try to get a substring.
indexOf()
当找不到参数时返回 -1。我敢打赌,您正在搜索的字符串没有您正在搜索的字符之一,并且在您尝试获取子字符串时会导致索引无效。
回答by Alex Stybaev
try to use contains()
before indexOf()
for yor string to avoid the situations when indexOf()
returns -1 and you try to get substring with the -1 position.
尝试对 yor 字符串使用contains()
beforeindexOf()
以避免indexOf()
返回 -1 并且您尝试获取具有 -1 位置的子字符串的情况。
回答by Dancrumb
String().indexOf
will return -1 if there is no match
String().indexOf
如果没有匹配,将返回 -1
String().substring
will throw an StringIndexOutOfBoundsException
if you give it a negative begin
value.
String().substring
StringIndexOutOfBoundsException
如果你给它一个负值会抛出一个begin
。
This is all documented at http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
这都记录在http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
Thus, I'd look at this line of code:
因此,我会看这行代码:
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
This will fail if usnm
is not in logindat
如果usnm
不在,这将失败logindat
回答by Xeon
You should really look at those lines:
你真的应该看看这些行:
int startUsnm = logindat.indexOf(usnm);
int tendUsnm = logdat.indexOf(':');
int endUsnm = startUsnm + tendUsnm;
int startPass = endUsnm + 1;
int tendPass = logdat.indexOf('.');
int endPass = startPass + tendPass;
String Usnm = logindat.substring(startUsnm, endUsnm);
String Pass = logindat.substring(startPass, endPass);
Suppose you have file like this:
假设你有这样的文件:
user:pass.
用户:通过。
so:
所以:
- startUsnm = 0 //first char
- tendUsnm = 4 // index of
:
char - endUsnm = 4 // sum? this is probably not what you intent to do
- startPass = 5 //
p
char - tendPass = 9 //
.
char - endPass = 14 // sum again? Those integers are indexes - will throw IndexOutOfBounds
- startUsnm = 0 //第一个字符
- tendUsnm = 4 //
:
字符索引 - endUsnm = 4 // 总和?这可能不是你想要做的
- startPass = 5 //
p
字符 - tendPass = 9 //
.
字符 - endPass = 14 // 再求和?这些整数是索引 - 将抛出 IndexOutOfBounds
And consider also that indexOf
will return -1
value if there is no such match in given String
.
并考虑如果在 given 中没有这样的匹配,那indexOf
将返回-1
值String
。
回答by Denys Séguret
A lot of things can be wrong. You'll have to check what is printed.
很多事情都可能是错误的。您必须检查打印的内容。
An exemple :
一个例子:
int startUsnm = logindat.indexOf(usnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
If you don't have "Username: " in logindat, it produces the exception you see.
如果您在 logindat 中没有“用户名:”,它会产生您看到的异常。
EDIT : Note that if you want to allow "username:" (and not only "Username:"), you can do this :
编辑:请注意,如果您想允许“用户名:”(而不仅仅是“用户名:”),您可以这样做:
int startUsnm = logindat.toLowerCase().indexOf("username:");
And test that startUsnm is >= 0.
并测试 startUsnm 是否 >= 0。