0

我有这样一个程序:

import java.util.Scanner; import java.io.*;

class C { public static void main (String[] args) throws IOException{

    System.out.println("Wpisz teks do zakodowania: ");

    String tekst;
        Scanner odczyt = new Scanner(System.in);
        tekst = odczyt.nextLine();
        System.out.println("Tekst odszyfrowany:" + tekst);
        char[]alfabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        int dlugalf=26;
        System.out.print("Tekst zaszyfrowany:");

        int a = 0;

        for(int i=0;;){

            System.out.print(tekst.charAt(a));
            a++;

        }
    }   
}

启动后,您应该查看问题并要求您输入文本。然后它应该显示我写的符号,并且程序必须单独加载每个字母,而不是整个字符串。但随后它会弹出一个错误:

Exception in thread "main" java.lang.StringIndexOut OfBoundsException: String index out of range: 10
at java.lang.String.charAt(Unknown Source)
at C.main(C.java:34)

它是由一个空字符串引起的。我怎样才能摆脱它?我试过这个命令:

if (!tekst.isEmpty() && tekst.charAt(0) == 'R');

但它没有成功。

如有错误请见谅;我不太会说英语。

4

2 回答 2

2

这段代码:

int a=0;
for(int i=0;;){

  System.out.print(tekst.charAt(a));
  a++;
}

应该成为

for(int a=0;a<tekst.length();a++){
     System.out.print(tekst.charAt(a));
}

实际上,您的循环将尝试永远进行。您用完了字符串中的字符(何时a=tekst.length())并且您得到了异常。

于 2016-03-28T19:21:47.500 回答
0

您似乎想通过不断变化来实现文本解密。

您的代码存在一些问题:

  1. 它不考虑大写字符和非字母
  2. 循环语句错误
  3. 没有解密

这是一个例子

final int shift = 1;//any shift here
final int alhpabetLength = 'z' - 'a';
String input = scanner.nextLine();
input = input.toLowerCase();
for (char c : input.toCharArray()) {
    if (c >= 'a' && c <= 'z') {
        int position = c - 'a';
        int decryptedPosition = (position + shift + alhpabetLength) % alhpabetLength;
        char decryptedC = (char)(decryptedPosition + 'a');
        System.out.print(decryptedC);
    } else {
        System.out.print(c);
    }
}

如果你使用shift = -1比加密线"ifmmp!",你会得到"hello!"

于 2016-03-28T19:50:38.090 回答