java - How to jump to 0 index of array if it will be exceeded in java?
问题描述
Let's say that i have an array of int's in range 65-90. I'll randomly pick one of elements and add 10 to it. Is it possible that value, if cross range of 90 return to 65? For example - i take a 85 and add 10 to it. So it should be 95, but i want a 70.
解决方案
You can do it by placing your value in the interval [0, high - low]
by removing low
to your value, then add the number you want to it, take the modulo of the sum, and finally add low
back to get back in the range [low, high]
public static void main(String[] args) {
int low = 65, high = 90;
System.out.println(addWithinInterval(85, 10, low, high));
}
private static int addWithinInterval(int value, int add, int low, int high) {
return (value - low + add) % (high - low + 1) + low;
}
推荐阅读
- android - Leanback VerticalGridView 高度:wrap_content
- php - Woocommerce api:使用图像创建产品 - 错误请求
- mysql - 表“测试”没有被锁定,即使它是
- google-bigquery - BigQuery 中的事务隔离级别是什么
- svn - SVN - 密码保护存储库中的每个项目
- java - Android 搜索小部件在单击后退按钮时失去焦点
- docker - 如何在 Traefik 代理后面安装 Harbor
- google-cloud-platform - gsutil ls 命令给出“OSError:权限被拒绝”
- asp.net-core-mvc - ASP.NET Core v1.1 中的 IdentityServer 和 Simple Injector 集成
- javascript - 如何通过反应上下文api传递多个状态