StringIndexOutOfBoundsException

StringIndexOutOfBoundsException

This question already has an answer here:
What is IndexOutOfBoundsException? How can I fix it? [duplicate]
                                
                                    (1个答案)
                                
                        
                                去年关闭。
            
                    
而我正在做一个简单的密码程序。我遇到这个错误

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)


好吧,我不清楚原因是什么。我需要一些资深人士的帮助,@@下面是我的代码。

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);
        }
}
}

最佳答案

这是您在for loop内的作业:-

char c = to.charAt(from.indexOf(line.charAt(i)));


在此,当在indexOf字符串中找不到-1时,在char中返回from,然后它将抛出StringIndexOutOfBoundsException

您可以在提取字符之前添加支票:-

int index = from.indexOf(line.charAt(i));

if (index >= 0) {
    char c = to.charAt(index);
    outPutText += c;
}


要么: -

char ch = line.charAt(i);

if (from.contains(ch)) {
    char c = to.charAt(from.indexOf(ch));
    outPutText += c;
}

关于java - 出现java.lang.StringIndexOutOfBoundsException错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13517711/

10-11 05:04