我想得到字符串的最后四个字符

时间:2015-03-11 00:44:52

标签: java string indexoutofboundsexception

我需要从字符串中获取最后四个字符,但每次输入内容时我都会获得StringIndexOutOfBoundsException。请帮我解决这个错误。

import java.util.Scanner;//need for Scanner
import java.io.*;
public class PansiyuA3Q2 {


  public static void main(String[] args)throws Exception { 
    Scanner autoFile = new Scanner(new File("AutoCorrectMe.txt"));
   String a =getFileName();
  }
  static String getFileName(){
    Scanner keyboard = new Scanner(System.in);//need for Scanner
    String a ="";//variable a
    String change = "";//get the last four character
    boolean valud ;//boolean valud
    int length = a.length();
    do{
      System.out.println("Enter the name of the file: ");//print Enter the name of the file:
       a= keyboard.nextLine();//get from user
       change = a.substring(length-4,length);
      if(change.equalsIgnoreCase(".txt"))//a equal autocrrectme.txt and ignore capital
        valud = true;//get true
      else //if a equal atuocorrectme and ignore capital
        System.out.println("The file name must end with .txt");//print The file name must end with .txt
      valud = false;//get false
    } while(!valud);//do while
    return a; 
  }//method getFilName

}

我可以编译它,但是当我运行程序时,无论我输入的是什么,都说它有错误。

java.lang.StringIndexOutOfBoundsException: String index out of range: -4
    at java.lang.String.substring(Unknown Source)
    at PansiyuA3Q2.getFileName(PansiyuA3Q2.java:22)
    at PansiyuA3Q2.main(PansiyuA3Q2.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

1 个答案:

答案 0 :(得分:1)

您在从用户那里获得length之前声明并初始化a

// int length = a.length();
do {
    System.out.println("Enter the name of the file: ");
    a = keyboard.nextLine();//get from user
    int length = a.length();
    if (length < 4) {
        continue; // <-- reloop if less then 4.
    }