[英]String Index Out of Bounds Exception Error for password program - NO arrays allowed
[英]String Index out of bounds error, basic program
这个程序做我想做的事情,但它也输出了一个巨大的错误。 其中的内容类似于“数组越界。字符串索引越界”。 该程序用于输入一个句子,并使用字母表中的不同字母(4个字符)重写它。 请帮我澄清这个错误!
public class Encryption
{
public static void main (String [] args)
{
System.out.print("Enter a message to encrypt: ");
String input = Console.readString();
for(int i = 0; i<100; i++)
{
char oldChar = input.charAt(i);
char encryptedChar = (char) (oldChar + 4);
System.out.print(encryptedChar);
}
}
如果得到StringIndexOutOfBoundsException
,那么输入的长度不是100个字符。
不要指望100个字符; 当i
达到你的弦长时,停止你的for
循环。
for (int i = 0; i < input.length(); i++)
输入总是一个100个字符的字符串,我相信不是,这就是错误。 用input.length()
替换100
改变你的循环边界。 如果用户键入少于100个字符,您将从i = 0循环到i = 99,这将超过输入长度。
for (int i = 0; i < input.length(); i++)
如前所述,您对循环进行了硬编码以迭代100个字符。 如果字符串不是100个字符怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.