2012-11-22 112 views
1

雖然我正在做一個簡單的密碼程序。我遇到這個錯誤獲取java.lang.StringIndexOutOfBoundsException錯誤

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

這不是一個密碼;) – LanguagesNamedAfterCofee

+0

「StringIndexOutOfBounds」,令人驚訝的,這意味着你使用的索引對一個無效的字符串操作(在本例中顯然是'charAt')。該消息甚至會告訴你什麼是無效索引:-1。將複雜的陳述分解爲更簡單的部分將允許您使用調試器或簡單的System.out.println語句檢查中間結果,併爲您自己解決問題。 –

回答

6

這是你的任務你for loop內: -

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

在這裏,indexOf回報-1from字符串沒有找到char,然後它會拋出一個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; 
} 
+2

@ shuffle1990 ..不客氣:)很高興你學到了一些東西。這就是犯錯的全部要點。乾杯:) –

3

如果在字符串中找不到字符,indexOf()返回-1。所以,你需要爲此發生一些偶然事件。當在「from」中找不到該字符時,您希望代碼執行什麼操作?