如何解决 "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5" Java 中的问题

How to fix "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5" problem in Java

我正在尝试创建一个代码,如果输入以 "Today" 开头并以 "MLIA" 结尾(大小写无关紧要),该代码将打印 "VALID ENTRY"。如果没有,则打印 "INCORRECT FORMATTING, TRY ANOTHER SUBMISSION"。由于某种原因,程序一直给我一个越界错误,我不知道为什么。

当我将子字符串代码更改为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 ==。否则它可以 return false 即使对于相同的 Strings.

其次,nextLine 将从 Scanner 开始读取,直到下一个换行符之后。但是 nextInt 只会读取到该换行符之前,因此您对 nextLine 的第一次调用只是将 Scanner 前进一个字符,并且 return 是一个空的 String .您需要在 nextInt 之后调用一个额外的 nextLine 以前进到您的整数之后的下一行。有关详细信息,请参阅 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");

}

您可以改用以下代码。

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

可以使用startsWith,nextInt之后需要调用nextLine,因为nextInt不读取换行符,在读取int 5后,curson保持在同一行。所以你得到了你所面临的错误。

当你放置一个额外的 nextLine() 它实际上移动到下一行。

之后你只有 5 行要读,你不需要 <= 否则它会在最后再次抛出错误。

所以make只有<

并且 startsWith() 如果您只需要检查开头就很好,如果您也想检查结尾那么还有一种方法 endsWith()

如果您想使用相等性,字符串还需要 equals 来与字符串文字匹配。