java - 我在尝试获取索引处的字符时遇到问题

标签 java indexing caesar-cipher

这是我的代码:

package ch3;

import java.util.Scanner;

public class caesarCypher {

    static String inp;

    public static void main(String[] args) {
        int input;
        int x = 0;
        Scanner scan = new Scanner(System.in);
        inp = scan.nextLine();

        input = inp.length();
        System.out.println(input + inp);
        while (x < input) {
            x += 1;
            inp =  ((inp.charAt(x)) - 12);
        }   
    }
}

我该如何将inp的索引设置为x?因此,换句话来说,我正在尝试减去该字符,例如 ASCII 表中的 a - 12。

最佳答案

尝试使用字符数组:

public class caesarCypher {

    static String inp;

    public static void main(String[] args) {
        int input;
        Scanner scan = new Scanner(System.in);
        inp = scan.nextLine();
        char[] inpArr = inp.toCharArray();

        input = inp.length();
        System.out.println(input + inp);
        for( int i = 0; i < input; i++)
        {
            inpArr[i] -= 12;
        }

        inp = new String( inpArr);
    }
}

顺便说一下,您将从下面的代码中获得一个 IndexOutOfBoundsExceptionn 。使用 x,然后递增它。

while (x < input) {
    x += 1;
    inp =  ((inp.charAt(x)) - 12);
}  

关于java - 我在尝试获取索引处的字符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39862825/

相关文章:

java - 需要凯撒密码中的代码解释

凯撒密码 C 程序 - 格式 %i 需要 int * 类型的参数,但具有 int 类型

java - 在 Applet 上绘图而不扩展 Applet 类

java - 我可以在外部类的构造函数中实例化一个匿名类吗?

sql - SQL Server 2008的填充因子

postgresql - 提高 PostgreSQL 查询的执行速度

python - 接收和旋转字符的函数 - Caesar Cipher

java - 我们如何在每日闹钟时打开我的应用程序。我可以使用 Pushregistry 作为每日闹钟吗

java - 当我想用真实设备测试我的应用程序时,该应用程序无法启动

java - Lucene通过ID检索文档速度慢