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

2 に答える 2

6

これはあなたの中であなたの割り当てfor loopです: -

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

ここで、文字列にが見つからない場合に in をindexOf返し、次に をスローします。-1charfromStringIndexOutOfBoundsException

文字を取得する前にチェックを追加できます: -

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;
} 
于 2012-11-22T17:42:20.533 に答える
3

問題の文字が文字列内に見つからない場合、indexOf() は -1 を返します。そのため、その発生に備えて、ある程度の不測の事態を組み込む必要があります。その文字が「from」に見つからない場合、コードに何をさせたいですか?

于 2012-11-22T17:40:30.050 に答える