obteniendo el error java.lang.StringIndexOutOfBoundsException [duplicado]
Esta pregunta ya tiene una respuesta aquí:
¿Qué es IndexOutOfBoundsException? ¿Cómo puedo arreglarlo? [duplicar] 1 respuestaMientras estoy haciendo un programa de cifrado simple. Me encontré con este error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(Unknown Source)
at Caesar.main(Caesar.java:27)
Bueno, no tengo muy claro cuál es la causa. Requiero ayuda de algún veterano aquí @@ a continuación está mi código.
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Caesar {
public static void main(String[] args){
String from = "abcdefghijklmnopqrstuvwxyz";
String to = "feathrzyxwvusqponmlkjigdcb";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
try{
FileReader reader = new FileReader("C:/"+inputFileName+".txt");
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter("C:/"+outputFileName+".txt");
while (in.hasNextLine()){
String line = in.nextLine();
String outPutText = "";
for (int i = 0; i < line.length(); i++){
char c = to.charAt(from.indexOf(line.charAt(i)));
outPutText += c;
}
System.out.println("Plaintext: " + line);
System.out.println("Ciphertext: " + outPutText);
out.println(outPutText);
}
System.out.println("Processing file complete");
out.close();
}
catch (IOException exception){
System.out.println("Error processing file:" + exception);
}
}
}