[英]How to fix “Exception in thread ”main“ java.lang.StringIndexOutOfBoundsException: String index out of range: 5” problem in Java
I'm trying to create a code that prints "VALID ENTRY" if the input begins with "Today" and ends with "MLIA" (case doesn't matter).如果输入以“Today”开头并以“MLIA”结尾(大小写无关紧要),我正在尝试创建一个打印“VALID ENTRY”的代码。 If it doesn't, then it prints "INCORRECT FORMATTING, TRY ANOTHER SUBMISSION".
如果没有,则打印“格式不正确,尝试其他提交”。 For some reason, the program keeps giving me an out-of-bounds error and I can't figure out why.
出于某种原因,程序不断给我一个越界错误,我不知道为什么。
When I changed the substring code to sub.substring(0,1)
to test it still gave me an error, so that is not the problem.当我将 substring 代码更改为
sub.substring(0,1)
进行测试时,它仍然给了我一个错误,所以这不是问题。 I also tried adding the char value for each letter to determine what the word was but that didn't work either.我还尝试为每个字母添加 char 值以确定单词是什么,但这也不起作用。
public class submit{
public static void main(String[] args) throws IOException{
Scanner scanner = new Scanner(new File("submit.txt"));
int trials = scanner.nextInt();
int total = 0;
for(int x = 0; x <= trials; x++){
String sub = scanner.nextLine();
sub = sub.toLowerCase();
if(sub.substring(0,5) == "today") //I only have it set up to find "today"
System.out.println("VALID ENTRY");
else
System.out.println("INCORRECT FORMATTING, TRY ANOTHER SUBMISSION");
}
}//end of main
}//end of class
Input:输入:
5
ToDAY, I went to school. mlia
Hehehe today mlia this shouldn't work
Today, I went to a programming contest. Hehe. MLIA
TODAYMLIA
T0day is a brand new day! MLIA
Expected output should be:预期的 output 应该是:
VALID ENTRY
INCORRECT FORMATTING, TRY ANOTHER SUBMISSION
VALID ENTRY
VALID ENTRY
INCORRECT FORMATTING, TRY ANOTHER SUBMISSION
Actual output:实际 output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.substring(String.java:1963)
at submit.main(submit.java:15)
There are two problems with the code.代码有两个问题。 First, you should compare
String
s using equals
, not ==
.首先,您应该使用
equals
来比较String
,而不是==
。 Otherwise it can return false even for identical String
s.否则,即使对于相同的
String
,它也可能返回 false 。
Second, nextLine
will read from the Scanner
up until after the next newline.其次,
nextLine
将从Scanner
读取直到下一个换行符之后。 But nextInt
only will read up until before that newline, so your first call to nextLine
simply advances the Scanner
by one character and returns an empty String
.但是
nextInt
只会读取到该换行符之前,因此您对nextLine
的第一次调用只需将Scanner
前进一个字符并返回一个空String
。 You need to call an extra nextLine
after nextInt
to advance onto the next line after your integer.您需要在
nextInt
之后调用一个额外的nextLine
以前进到 integer 之后的下一行。 For more information, see this question .有关详细信息,请参阅此问题。
So you should make the following changes to your code:因此,您应该对代码进行以下更改:
Scanner scanner = new Scanner(new File("submit.txt"));
int trials = scanner.nextInt();
scanner.nextLine(); //Add this line, to consume the newline character after "5"
// alternatively, you could replace both of the above lines with this:
// int trials = Integer.parseInt(scanner.nextLine());
int total = 0;
for(int x = 0; x <= trials; x++){
String sub = scanner.nextLine();
sub = sub.toLowerCase();
if(sub.substring(0,5).equals("today")) //compare strings using equals, not ==
System.out.println("VALID ENTRY");
else
System.out.println("INCORRECT FORMATTING, TRY ANOTHER SUBMISSION");
}
You can use the following code instead.您可以改用以下代码。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Submit {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("submit.txt"));
int trials = scanner.nextInt();
scanner.nextLine();
int total = 0;
for (int x = 0; x < trials; x++) {
String sub = scanner.nextLine();
sub = sub.toLowerCase();
System.out.print(sub + " -> ");
if (sub.startsWith("today")) // I only have it set up to find "today"
System.out.println("VALID ENTRY");
else
System.out.println("INCORRECT FORMATTING, TRY ANOTHER SUBMISSION");
}
scanner.close();
}// end of main
}// end of class
You can use the startsWith and nextLine needs to be called after nextInt because nextInt does not read the newline character and keeps the curson on the same line after the int 5 is read.您可以使用 startsWith 并且 nextLine 需要在 nextInt 之后调用,因为 nextInt 不读取换行符并且在读取 int 5 后将光标保持在同一行。 So you get that error that you are facing.
所以你得到了你所面临的错误。
When you put an extra nextLine()
it actually moves to next line.当您放置一个额外的
nextLine()
时,它实际上会移动到下一行。
After that you have only 5
lines to read and you don't need <=
otherwise it will throw error in the end again.之后你只有
5
行要阅读,你不需要<=
否则它会再次抛出错误。
So make is <
only所以 make 是
<
only
And startsWith()
is good if you only have to check the beginning and if you want to check end too then there is a method endsWith()
as well如果您只需要检查开头并且还想检查结尾,那么
startsWith()
就很好,那么还有一个方法endsWith()
Also the string needs equals
for matching with string literals if you want to use the equality.如果要使用相等,字符串也需要
equals
才能与字符串文字匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.