2016-04-25 34 views
0

應該發生什麼是當輸入-2被要求'輸入數字到decrpyt'將結束while循環,並在此之後打印result2(解密字)。相反-2產生錯誤 'java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-2'解密時出錯while循環

如何繞過此?

import java.util.Scanner; 

public class Decrypt { 

    public static void main(String[] args) { 

     Scanner sc; 
     int result, input2, num, end = -2; 
     String word, sourcetext, answer, encrypt = "1", decrypt="2"; 

     char input, result2; 
     sc = new Scanner(System.in); 

     System.out.println("please enter sourcetext"); 
     sourcetext = sc.nextLine(); 

     System.out.print("Would you like to 1: encrypt, or 2: decrypt?"); 
     answer = sc.next(); 

     System.out.println("please enter numbers to decrypt"); 
     while (answer.equals(decrypt)) { 

      num = sc.nextInt();     // number to decrypt 
      result2 = sourcetext.charAt(num);  // num decrypted 

      if (num <= end) {      // int end = -2 

       System.out.print(result2); 

      } 

     } 
    } 
} 
+0

只是檢查是否輸入的號碼,NUM,低於零前行 'RESULT2 = sourcetext.charAt(NUM);'或使用try..catch –

+0

仍拋出異常'java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-2' – Button

+0

你不能有-2作爲字符串的索引 –

回答

0

當輸入-2,它傳遞一個到charAt會拋出異常,因爲沒有-2指數的字符串中。您應該將if (num <= end)塊移到while循環的開始位置,並將其餘部分放到else塊中。

像這樣:

if (num <= end){      
    System.out.print(result2); 
} else { 
    num = sc.nextInt();     // number to decrypt 
    result2 = sourcetext.charAt(num);  // num decrypted 
} 
+0

result2的值是什麼? –

+0

問題在於num和result2將不會被初始化,並會在if語句中引發錯誤。 Rakesh,result2將顯示用戶輸入的數字,使用源文本中字母的位置進行解密。 – Button

+0

@Button然後你需要給'result2'一個默認值或者重寫你的邏輯。關鍵是你不能在'charAt'方法中產生一個負向索引,這就是你遇到錯誤的原因。現在知道這一點,你應該能夠重新工作你的代碼,以避免這種情況。我不會爲你重寫你的程序。 – kunruh