【问题标题】:Why is my code giving me an out of range exception? [closed]为什么我的代码给了我一个超出范围的异常? [关闭]
【发布时间】:2016-03-28 19:04:58
【问题描述】:

我有这样一个程序:

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

但它没有成功。

如有错误,请见谅;我的英语不太好。

【问题讨论】:

  • 好吧,我不知道这篇文章是什么语言,但我可以看到你正在通过在索引 a 处获取一个字符来进行无限循环打印a 最终会超出您的数组范围

标签: java helpers polish


【解决方案1】:

这段代码:

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() 时)并且您得到了异常。

【讨论】:

  • 哦.... C.java:34: 错误:找不到符号 for(int a=0;a
  • @tomcio61 抱歉我忘了()
【解决方案2】:

看来你想用常量移位来实现文本解密。

您的代码存在一些问题:

  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!"

【讨论】:

  • 正是我的观点。但我希望同样的事情发生。没有最终代码:D
  • 学习东西的最好方法是分析它。您可以将代码粘贴到您的项目中,逐行调试几次,仔细观察值。比你可以删除粘贴的代码并自己重写它。
  • 这是个好主意。
  • 我有这个错误:C.java:32: error: possible loss of precision char decryptedP = (position + shift + da lf) % dalf; ^ 必需:找到的字符:int C.java:33:错误:可能丢失精度 char decryptedC = decryptedP + 'a'; ^ 必需:找到的字符:int 2 错误
  • 更新了我的答案。如果对您有帮助,您可以将其标记为答案
猜你喜欢
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多