【问题标题】:String Index out of range: 1字符串索引超出范围:1
【发布时间】:2018-03-30 17:19:30
【问题描述】:
    Scanner user_input = new Scanner( System.in );

    String cipher_input = user_input.nextLine();
    String[] arr_cipher_input = cipher_input.split("");

    int[] arr_ctext = new int[cipher_input.length()];
    for (int i = 0; i < cipher_input.length(); i++) {
        arr_ctext[i] = (int) arr_cipher_input[i].charAt(i);
    }

上面的代码接受一个输入并将其拆分为一个数组(例如,“hello”变为 [“h”,“e”,“l”,“l”,“o”]),然后我尝试将字符到它们的 ascii 值,这是它在标题中返回错误的地方。它每次都正确转换第一个字符,然后在第二个字符上停止,我似乎不知道为什么。数组长度似乎相同,所以我不确定我做错了什么。我会很感激任何帮助。提前致谢!

【问题讨论】:

    标签: java arrays string int


    【解决方案1】:

    您正在创建多个单个字符String(s)。但是您正在尝试访问后续字符。没有。将charAt(i) 更改为charAt(0) 进行修复。喜欢,

    arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
    

    (更有效)跳过split 并直接访问输入中的字符。喜欢,

    String cipher_input = user_input.nextLine();
    int[] arr_ctext = new int[cipher_input.length()];
    for (int i = 0; i < cipher_input.length(); i++) {
        arr_ctext[i] = (int) cipher_input.charAt(i);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 2011-07-23
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2013-05-13
      相关资源
      最近更新 更多