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
}
I can compile it but when I run the program ,whatever the word I input .it says there is a error. 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)
Aucun commentaire:
Enregistrer un commentaire