如何在Java中修复“线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5”的问题

时间:2019-09-18 20:07:23

标签: java substring charat

如果输入以“ 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)

2 个答案:

答案 0 :(得分:0)

代码有两个问题。首先,您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");

}

答案 1 :(得分:0)

您可以改用以下代码。

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和nextLine在nextInt之后调用,因为nextInt不会读取换行符,并且在读取int 5之后将光标保留在同一行。这样您就可以解决所面临的错误。

当您额外输入nextLine()时,它实际上会移至下一行。

此后,您只需要读取5行,就不需要<=,否则它将再次导致错误。

所以make仅<

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

如果您想使用等号,则字符串还需要equals与字符串文字进行匹配。