Ant*_*uly 4 java arrays modulus
我有一个关于使用按钮切换一些图像的教程,这是代码
public class MainActivity extends AppCompatActivity {
private static ImageView andro;
private static Button buttonswitch;
int current_image_index = 0;
int[] images = {R.mipmap.andro_img,R.mipmap.apple_image,R.mipmap.ic_launcher,R.mipmap.ic_launcher_round};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
public void buttonClick() {
andro = (ImageView) findViewById(R.id.imageView);
buttonswitch = (Button) findViewById(R.id.button);
buttonswitch.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
}
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
这部分我真的很困惑:
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
Run Code Online (Sandbox Code Playgroud)
我的理解是,一旦我点击按钮,那么 int current_image_index 将增加 1。然后模 current_image_index 与 images.length 它将使 current_image_index 的余数除以 image.length。例如,第一次我将current_image_index = 0,然后一旦单击,它将为1,然后current_image_index % image.length = 0。然后andro.setImageResource(images[0]);
这将一次又一次地重复,因为 current_image_index 保持为 0。那么一旦单击图片,图片如何不断变化,因为 current_image_index%image.length 将始终给出 0 的结果。
...因为 current_image_index%image.length 将始终给出 0 结果。
不完全正确。
取模运算符 ( %) 计算两个操作数的余数。这是一种重复的减法。事实上,a % b你会问自己:
如果我再说一遍减去什么数量仍然
b从a直到操作不再可能?
让我们用8 % 3(soa = 8和b = 3)测试它。
从逻辑上讲,a % b带有 result的操作r总是会产生 0 <= r < b。
示例:
5 % 2 = 1(因为 4 ÷ 2 = 2,余数为 1)
17 % 6 = 5(因为 12 ÷ 6 = 2,余数为 5)
20 % 4 = 0(因为 20 ÷ 4 = 5什么都没有留下)
因此,在您的情况下,数组索引始终至少0为images.length - 1。这正是数组的有效范围。
假设您有3张图像,因此images.length是3。也current_image_index被初始化为0。所以你会image[0]在一开始就看到。
current_image_index增加到1。然后,应用模数运算:1 % 3 = 1。current_image_index增加到2。然后,应用模数运算:2 % 3 = 2。current_image_index增加到3。然后,应用模数运算:3 % 3 = 0。这意味着索引达到3,但随后立即被模数运算符重置为0。所以之后image[2],image[0]显示。您会看到从 0 而不是 1 开始的索引现在对我们有好处。
| 归档时间: |
|
| 查看次数: |
8569 次 |
| 最近记录: |