简体   繁体   中英

Scala , java “for” in scala

I don't know how convert java "continue" to scala. I can use marker from bool + break , but its bad idea Google did not help :( It's my first program in scala... yep.. it's horrible

sort java

def sort(in: Array[Int], a:Int, b:Int)
  {
     var i,j,mode;
     double sr=0;
     if (a>=b) return;                                     // size =0
     for (i=a; i<=b; i++) sr+=in[i];
     sr=sr/(b-a+1);
     for (i=a, j=b; i <= j;)
            {
            if (in[i]< sr) { i++; continue; }        // left > continue
            if (in[j]>=sr) { j--; continue; }         // right, continue
            int c = in[i]; in[i] = in[j]; in[j]=c;
            i++,j--;                                       // swap and continue
            }
     if (i==a) return;
     sort(in,a,j); sort(in,i,b);
  }

sort scala...

def SortMerger(in:List[Int], a:Int, b:Int):Unit = {
    var i = 0;
    var j = 0;
    var mode = 0;
    var sr = 0.0;
    if(a>=b) return;
    i=a
    while(i<=b)
    {
      sr+=in.ElementOf(i);
      i += 1
    }
    sr=sr/(b-a+1)
    i=a
    j=b
    while(i<=j)
    {
      if(in.ElementOf(i)<sr) {
        i += 1; 
        // where continue??? ><
        }
    }

    return
  }

Scala has no continue statement, but what you are trying to do can be done with a simple if/else structure.

while(i<=j) 
{
  if(in(i) < sr) {
   i += 1
  } else if (in(j) >= sr) {
    j -= 1
  } else {
    int c = in(i)
    in(i) = in(j)
    in(j) = c
    i += 1
    j -= 1
  }
}

Note that the type of in here should be Array , not List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM