java - 我需要帮助理解 java.lang.StringIndexOutOfBoundsException

标签 java android

我为凯撒密码编写了代码,但它不起作用...请帮我解决这个问题。

import java.io.IOException;
import java.util.Scanner;

public class test1 {

    public static void main(String[] args) throws IOException {
        System.out.println("enter the String");
        StringBuffer str = new StringBuffer(new Scanner(System.in).nextLine());
        System.out.println("encrypting the String . . ." +str);

        for(int j=0; j<str.length(); j++){
            for(int i=0; i<256; i++) {
                if((char)i == str.charAt(j)){
                    str.setCharAt(j, (char)(i+3));
                }
            }
        }
        System.out.println("encrypted String . . .");
    }
}

这里您的解决方案有效,不再有 java.lang.StringIndexOutOfBoundsException 现在又出现了一个问题。 . . . 我尝试了不同的输入,但它始终回复相同的答案:??????

最佳答案

使用for(int j=0; j<str.length(); j++) // string index length are 0 based

代替

for(int j=0; j<=str.length(); j++)

关于java - 我需要帮助理解 java.lang.StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28447925/

相关文章:

android - 如何修复实体和 POJO 必须有可用的公共(public)构造函数

java - 系统命令无法从程序执行

java - 检查 ArrayList 中整数的更简洁方法?

java - "No mapping found for HTTP request"当我更改 DispatcherServlet 的路径时

android - 在 Android 问题上远程调试 Chrome

android - 处理程序不调用

android - 不要在主题中请求 Window.FEATURE_ACTION_BAR 并将 windowActionBar 设置为 false 以使用工具栏

java - 如何使用 Processing for Android 提高性能?

java - 从 java 调用时 shell 脚本中的 Scrapy 命令不执行

java - 可能的内联 "pre-assignment"操作?