我遇到了一些包含以下内容的代码%
数组参数内的符号。
它是什么意思以及它是如何工作的?
Example:
String[] name = { "a", "b", "c", "d" };
System.out.println(name[4 % name.length]);
System.out.println(name[7 % name.length]);
System.out.println(name[50 % name.length]);
Output:
a
d
c
这就是余数运算符 https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3,它给出整数除法的余数。例如,3 % 2
is 1
因为剩下的3 / 2
is 1
.
它被用来将值保持在范围内:如果name.length
小于 4、7 或 50,则结果% name.length
这些值是在范围内的值0
to name.length - 1
.
因此,即使数字(4、7 或 50)超出范围,代码也能可靠地从数组中选取条目。4 % 4
is 0
, 7 % 4
is 3
, 50 % 4
is 2
。所有这些都是有效的数组索引name
.
完整示例(实时复制 http://ideone.com/JEGhlu):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
String[] name = { "a" , "b" , "c" , "d"};
int n;
n = 4 % name.length;
System.out.println(" 4 % 4 is " + n + ": " + name[n]);
n = 7 % name.length;
System.out.println(" 7 % 4 is " + n + ": " + name[n]);
n = 50 % name.length;
System.out.println("50 % 4 is " + n + ": " + name[n]);
}
}
Output:
4 % 4 is 0: a
7 % 4 is 3: d
50 % 4 is 2: c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)