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

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

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

问题

  1. for (i in 0 until arrTriple!!.size){
  2. if (arrTriple[i].third >= ordertime){
  3. // 需要获取这个值,同时避免数组越界: arrTriple[i+1].third
  4. // 这样我就可以在这里使用我的逻辑。
  5. }
  6. }```
  7. <details>
  8. <summary>英文:</summary>
  9. 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.
  10. 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.
  11. Code :
  12. ```val arrTriple = PREMIUMHM[itemname.toUpperCase(Locale.getDefault())]
  13. for (i in 0 until arrTriple!!.size){
  14. if (arrTriple[i].third &gt;= ordertime){ //arrTriple[i].third is time when when I change price
  15. //Need this value also without getting indexoutofbond = arrTriple[i+1].third
  16. //So I can use my logic here.
  17. }
  18. }
  19. </details>
  20. # 答案1
  21. **得分**: 0
  22. 我理解你的问题了。你可以从 i = 1 开始,并且将 i-1 替换为 i+1 吗?类似这样:
  23. ```kotlin
  24. for (i in 1 until arrTriple!!.size) {
  25. if (arryTriple[i-1].third >= overtime) {
  26. arrTriple[i].third
  27. }
  28. }

你会遇到一个特殊情况,即 arrTriple.size == 1,你需要处理它。

编辑:

否则,只需添加一个 if 检查:

  1. for (i in 0 until arrTriple!!.size){
  2. if (arrTriple[i].third >= ordertime && (i+1) < arrTriple.size) {
  3. }
  4. }
英文:

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:

  1. for (i in 1 until arrTriple!!.size) {
  2. if (arryTriple[i-1].third &gt;= overtime {
  3. arrTriple[i].third
  4. }
  5. }

You'll have an edge case where arrTriple.size == 1 that you'd need to handle still.

EDIT:

Otherwise, just add an if-check.

  1. for (i in 0 until arrTriple!!.size){
  2. if (arrTriple[i].third &gt;= ordertime &amp;&amp; (i+1) &lt; arrTriple.size){
  3. }
  4. }

答案2

得分: 0

你不一定需要until关键字。你可以像这样编写:

  1. for (element in arrTriple!!) {
  2. if (element.third >= ordertime) {
  3. // 在这里添加你的逻辑
  4. }
  5. }

这是我的方法。

英文:

You don't necessarily need until. You would write it just like this

  1. for(element in arrTriple!!){
  2. if(element.third &gt;= ordertime){
  3. // Your logic here
  4. }
  5. }

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:

确定