初始化时post Increment ++ Operator如何工作 [英] How post Increment ++ Operator works while initialization

查看:100
本文介绍了初始化时post Increment ++ Operator如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来反转给定的字符串:

I have written following code to reverse the given String:

String str = "abcdef";
char[] strToChar = str.toCharArray();
char[] outString = new char[strToChar.length];

for(int j = 0; j < strToChar.length; ) {
    int len = strToChar.length-j;
    outString[j++] = strToChar[strToChar.length-j];
}

据我了解,初始化发生在之间.因此,此处的strToChar[strToChar.length-j]应该抛出ArrayIndexOutOfBoundException.

As per my understanding initialization happens from Right to Left. Hence, strToChar[strToChar.length-j] here should throw ArrayIndexOutOfBoundException.

但是运行正常.这是怎么回事?它不应该对此进行评估吗?

But it runs fine. How is that happening? Shouldn't it evaluate to this?

outString[0] = strToChar[6];    //This should throw exception

推荐答案

如果我查看您的代码,则您已将条件写为

If I look at your code, then you have written your condition to be

for(int j = 0; j < strToChar.length;) 

此处 strToChar.length 将返回数组的实际长度为6.

here strToChar.length will return you the actual length of the array which is 6.

使用for循环迭代数组的正确方法是:

The correct way to iterate an array with for loop would be:

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

索引从0开始到< strToChar.length

The index starting from 0 and going to < strToChar.length

这篇关于初始化时post Increment ++ Operator如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆