简体   繁体   中英

Counting indexes by using a while-loop

The task is to count the negative numbers by using a while-loop. (The task before was to count them by using a for-loop). When I tried earlier the sum of all negative numbers was 0, but it has to be 3... Someone help?

class NegativeTall{

    public static void main(String[] args){

    int[] a = {1, 4, 5, -2, -4, 6, 10, 3, -2};

    //a
    int teller = 0;

    for (int i = 0; i<a.length; i++){
        if (a[i]<0){
        teller = teller + 1;
        }
    }
    System.out.println("Antall negative tall er: "+teller);
    //


    **//b
    teller = 0;
    int j = 0;
    while (???){
        ???
        ???
    }
    System.out.println("Antall negative tall er: "+teller);
    //**

    }
}

The following should work just fine:

while(j<a.length)//while end of array have not been reached
{
    if (a[j]<0)
       teller = teller + 1;

    j++;//increment j        
}

Here's your class copy with solution:

class NegativeTall{

    public static void main(String[] args){

    int[] a = {1, 4, 5, -2, -4, 6, 10, 3, -2};

    //a
    int teller = 0;

    for (int i = 0; i<a.length; i++){
        if (a[i]<0){
        teller = teller + 1;
        }
    }
    System.out.println("Antall negative tall er: "+teller);
    //


    **//b
    teller = 0;
    int j = 0;
    while (j<a.length){
        if(a[j]<0){
        teller++;
       }
       j++;
    }
    System.out.println("Antall negative tall er: "+teller);
    //**

    }
}

Output Of While Loop:

Antall negative tall er: 3

The first for statement can be expressed in a more elegant way:

for (int n : a)
{
  if (n < 0)
  {
    teller += 1;
  }
}

The equivalent using a while loop maybe:

int j = 0;    
while (j < a.length)
{
  if (a[j++] < 0)
  {
    teller += 1;
  }     
}

However, the while loop is less readable in this case. Also, it needs an external variable (j) that's not really needed outside the while body, adding dirty variables exposed to the rest of the function's body.

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