gpt4 book ai didi

java - Java中如何解决“线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5”的问题

转载 作者:行者123 更新时间:2023-12-02 00:32:36 25 4
gpt4 key购买 nike

我正在尝试创建一个代码,如果输入以“ Today”开头并以“ MLIA”结尾(大小写无关),则打印“ VALID ENTRY”。如果不是,则打印“格式不正确,请尝试其他提交”。由于某种原因,该程序不断给我一个越界错误,我不知道为什么。

当我将子字符串代码更改为sub.substring(0,1)进行测试时,仍然给我一个错误,所以这不是问题。我还尝试为每个字母添加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


输入:

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


预期输出应为:

VALID ENTRY  
INCORRECT FORMATTING, TRY ANOTHER SUBMISSION
VALID ENTRY
VALID ENTRY
INCORRECT FORMATTING, TRY ANOTHER SUBMISSION


实际输出:

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)

最佳答案

代码有两个问题。首先,您should compare Strings using equals, not ==。否则,即使对于相同的String,它也可能返回false。

其次,nextLine将从Scanner读取直到下一个换行符之后。但是nextInt只会读到该换行符之前,因此您第一次调用nextLine只是将Scanner前进一个字符并返回一个空的String。您需要在nextLine之后调用一个额外的nextInt,以前进到整数之后的下一行。有关更多信息,请参见this question

因此,您应该对代码进行以下更改:

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

}

关于java - Java中如何解决“线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5”的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58000049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com