Java / Kotlin getting value in for loop for step + one and also a step before if condition in for loop

huangapple go评论111阅读模式
英文:

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 &gt;= 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 &gt;= 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 &gt;= ordertime &amp;&amp; (i+1) &lt; 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 &gt;= ordertime){ 
        // Your logic here
    }
}

This would be my approach

huangapple
  • 本文由 发表于 2020年8月24日 02:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63550540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定