【问题标题】:getting java.lang.StringIndexOutOfBoundsException error [duplicate]获取 java.lang.StringIndexOutOfBoundsException 错误 [重复]
【发布时间】:2012-11-22 17:38:55
【问题描述】:

当我在做一个简单的密码程序时。我遇到了这个错误

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

【问题讨论】:

  • "StringIndexOutOfBounds",令人惊讶的是,这意味着您在无效的字符串操作(在这种情况下显然是 charAt)上使用了索引。该消息甚至告诉您无效索引是什么:-1。将复杂的语句分解成更简单的部分可以让您使用调试器或简单的 System.out.println 语句检查中间结果并自己解决。

标签: java


【解决方案1】:

这是你在for loop 中的任务:-

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

这里,在indexOf中,当charfrom字符串中没有找到时,返回-1,然后它会抛出一个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;
} 

【讨论】:

  • @shuffle1990.. 不客气 :) 很高兴你学到了一些东西。这就是犯错的全部意义所在。干杯:)
【解决方案2】:

indexOf() 如果在字符串中找不到相关字符,则返回 -1。因此,您需要为这种情况的发生建立一些应急措施。当在“from”中找不到字符时,你想让代码做什么?

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 2018-09-07
    • 2023-03-18
    • 2014-05-18
    • 2015-12-02
    • 1970-01-01
    • 2018-09-14
    相关资源
    最近更新 更多