首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java索引5在执行while循环时长度5错误超出界限

java索引5在执行while循环时长度5错误超出界限
EN

Stack Overflow用户
提问于 2022-11-02 06:15:41
回答 4查看 55关注 0票数 0

我试图用最近的偶数索引字符在字符串中将每个奇数索引字符切换到它。

代码语言:javascript
复制
public class A3_Q1 {

    public static void main(String... args) {
        System.out.print("Enter the messgae you want to be coded: ");
        
        Scanner in = new Scanner(System.in);
        String msg = in.nextLine();
        
        in.close();
        
        msg = msg.trim();
        char msg1[] =  msg.toCharArray();
        int index = 0;
        
        while (index<msg.length()) {
            msg1[index] = msg1[++index];
            index++;
        }
    
        System.out.print(msg1); 
    }

}

我试着去找更有经验的朋友,问他们出了什么问题,但我们都不知道是怎么回事。

EN

回答 4

Stack Overflow用户

发布于 2022-11-02 07:16:12

如果索引是msg.length() -1,会发生什么情况?你会越界的。

因此,您应该检查循环中的两个条件。

  1. 索引是奇数或偶数
  2. 索引,index + 1不是超出限制范围的指数。
票数 1
EN

Stack Overflow用户

发布于 2022-11-02 07:44:56

++index在使用该值之前先增加索引。index++在增量之前首先使用该值。这意味着每次迭代都会使index增加2。如果msg有一个奇数长度(您的示例5),并且index = 4,则进入循环。[++index]被计算为[5],您将得到异常。

因此,您必须忽略while (index<msg.length() - 1)的最后一个奇数字符。

票数 0
EN

Stack Overflow用户

发布于 2022-11-02 06:26:42

代码语言:javascript
复制
public static void main(String... args) {
    // Best practice: one instruction per one line
    System.out.print("Enter the message you want to be coded: ");

    // When using System.in you should not close the Scanner
    Scanner scan = new Scanner(System.in);
    String message = scan.nextLine().trim();
    // Best practice: move encoding logic to the separate method
    String convertedMessage = convert(message);
    System.out.println(convertedMessage);
}

public static String convert(String str) {
    // String is immutable, so we have to use StringBuilder to build a new string
    StringBuilder buf = new StringBuilder();

    // does not matter what to use, I prefer for...loop
    for (int i = 0; i < str.length(); i++) {
        // do not forget to check case for the last index
        if (i == str.length() - 1 || i % 2 != 0)
            buf.append(str.charAt(i));
        else
            // here we have odd and not last index (just use the next one)
            buf.append(str.charAt(i + 1));
    }

    return buf.toString();
}

Demo

代码语言:javascript
复制
Enter the message you want to be coded: abcdefghijklmnopqrstuvwxyz
bbddffhhjjllnnpprrttvvxxzz
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74285043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档