英文:
Java / Kotlin getting value in for loop for step + one and also a step before if condition in for loop
问题
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime){
// 需要获取这个值,同时避免数组越界: arrTriple[i+1].third
// 这样我就可以在这里使用我的逻辑。
}
}```
<details>
<summary>英文:</summary>
I am currently creating a program to check the order status (pending or confirmed) when a user open the app now the problem is if I need to check after order time and between I am checking time (Current Time) in this timeframe check for how many times I change price and compare if price is match or not.
So how can I check a step before i. like i is 3 and I need to also include 2 in it and compare value of i and i+1 value in every loop without getting index out of bond.
Code :
```val arrTriple = PREMIUMHM[itemname.toUpperCase(Locale.getDefault())]
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime){ //arrTriple[i].third is time when when I change price
//Need this value also without getting indexoutofbond = arrTriple[i+1].third
//So I can use my logic here.
}
}
</details>
# 答案1
**得分**: 0
我理解你的问题了。你可以从 i = 1 开始,并且将 i-1 替换为 i+1 吗?类似这样:
```kotlin
for (i in 1 until arrTriple!!.size) {
if (arryTriple[i-1].third >= overtime) {
arrTriple[i].third
}
}
你会遇到一个特殊情况,即 arrTriple.size == 1
,你需要处理它。
编辑:
否则,只需添加一个 if 检查:
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime && (i+1) < arrTriple.size) {
}
}
英文:
Think I understand what you're asking. Can you start with i = to 1 and do i-1 instead of i+1? Something like this:
for (i in 1 until arrTriple!!.size) {
if (arryTriple[i-1].third >= overtime {
arrTriple[i].third
}
}
You'll have an edge case where arrTriple.size == 1
that you'd need to handle still.
EDIT:
Otherwise, just add an if-check.
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime && (i+1) < arrTriple.size){
}
}
答案2
得分: 0
你不一定需要until
关键字。你可以像这样编写:
for (element in arrTriple!!) {
if (element.third >= ordertime) {
// 在这里添加你的逻辑
}
}
这是我的方法。
英文:
You don't necessarily need until
. You would write it just like this
for(element in arrTriple!!){
if(element.third >= ordertime){
// Your logic here
}
}
This would be my approach
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论