数组中的正结果计数

时间:2015-11-11 21:32:24

标签: java arrays

好的,所以我有这个问题,我必须在表中输出所有值都小于5且大于-1的计数行。现在它只输出表和1和2(这是正确的)。代码有效,但我如何才能显示正面结果的数量(在这种情况下为2)?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class Ld4151rdb258 {
    public static void main(String[] args) {
        int A[][] = {
            {0,1,2,0,2},
            {4,4,4,4,4},
            {0,-1,8,10,-1},
            {0,3,-1,2,1},
            {4,8,4,8,12},
            {-1,-1,2,0,1},
            {1,8,2,4,-1},
            {8,16,-1,4,0}
        };
        int i, j;
        int fiveCount, lowCount;
        char ch = 'n';

        System.out.print("fill with random numbers(y/n)? ");
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in)
        );

        try {
            ch = (char)br.read();
        }
        catch (IOException e) {
            System.out.println("input-output error");

            return;
        }

        Random rnd = new Random();

        if (ch=='Y' || ch=='y') {
            for (i=0; i<8; i++)
                for (j=0; j<5; j++) 
                    A[i][j] = rnd.nextInt(21);
        } else if (ch != 'N' && ch != 'n') {
            System.out.println("input-output error");

            return;
        }

        for (i=0; i<8; i++) {
            for (j=0; j<5; j++)
                System.out.print(A[i][j] + "\t");
                System.out.println();
        }

        System.out.println("results: ");

        for (i=0; i<8; i++) {
            fiveCount = 0;
            lowCount = 0;

            for (j=0; j<5; j++) {
                if (A[i][j] <= 5) fiveCount++;
                if (A[i][j] == -1)  lowCount++;
            }

            if (fiveCount == 5 && lowCount == 0)
                System.out.print((i+1) + " ");
        }
    }
}    

1 个答案:

答案 0 :(得分:0)

    int numRows = 0;
    for (i=0; i<8; i++) {
        fiveCount = 0;
        lowCount = 0;

        for (j=0; j<5; j++) {
            if (A[i][j] <= 5) fiveCount++;
            if (A[i][j] == -1)  lowCount++;
        }

        if (fiveCount == 5 && lowCount == 0) {
            System.out.print((i+1) + " ");
            numRows++;
        }
    }
    System.out.println();
    System.out.println("Count of the positive results " + numRows);