Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

While I am doing a simple cipher program I have encountered this 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)

Well, I am not quite clear what is the cause. I require some help from someone. This is my code.

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

        }

}

}

1 Answer

0 votes
by (13.1k points)

This is your assignment inside your for loop:

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

Here, in indexOf returns -1 when the char is not found in from string, and then it will throw an StringIndexOutOfBoundsException.

You can add a check before fetching the character:

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

if (index >= 0) {

    char c = to.charAt(index);

    outPutText += c;

}

Or

char ch = line.charAt(i);

if (from.contains(ch)) {

    char c = to.charAt(from.indexOf(ch));

    outPutText += c;

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Mar 13, 2021 in Java by Jake (7k points)
0 votes
1 answer

Browse Categories

...