なぜシーザーの暗号化の問題が動作していないではないのですか?

グウェンLS:

私は大学のための割り当てのために、このループを実行しているとの問題を抱えています。これは、最初の文字の正しいを与える最初のものを実行しますが、endIndexには何とか範囲外であるため、エラーを与えます。私は複数のものを調整しようとしましたが、それはまだ動作しません。

これはエラーです:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.substring(String.java:1963)
    at Assignment4.Question4.main(Question4.java:18)

私のコード:

package Assignment4;

import java.util.Scanner;

public class Question4 {

  public static void main(String[] args) {      
    Scanner in = new Scanner(System.in);
    System.out.print("Type a string: ");
    String message = in.nextLine();
    System.out.print("Type a key of the same length: ");
    String key = in.nextLine();
    in.close();

    int messageLength = message.length();

    for (int a = 0, b = 1; a < messageLength && b <= messageLength; a++, b++) {
      key = key.substring(a,b);
      message = message.substring(a,b);
      System.out.print(String.valueOf((char)(message.charAt(0) + Integer.parseInt(key))));
    }
  }

}
akuzminykh:

あなたは、変数をオーバーライドしているkeyあなたのループに。

for (int a = 0, b = 1; a < messageLength && b <= messageLength; a++, b++) {
      key = key.substring(a,b);

最初の反復は、あなたの初期の値の非常に最初の文字与えkeyおよび「オーバーライド」keyこの文字によると。次の反復a == 1とは、b == 2原因となりますStringIndexOutOfBoundsExceptionので、key唯一の長さ1を有しています。


FYI:同じエラーがによって引き起こされますmessage


問題を解決するには、一時的な結果および最終結果を格納するための追加の変数が必要になります。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=345147&siteId=1