如何通过java中的条件将数组的索引插入另一个数组

时间:2016-11-30 21:09:14

标签: java arrays

编写一个包含3个数组的java程序。第一个数组将存储50到100的随机整数值列表。程序将识别传递值和失败值。第二个数组将包含所有传递的值。第三个数组将包含所有失败的值。所需输入包括数组大小和通过等级。输出如下:原始列表,通过的成绩列表和失败成绩列表。 我知道这不是最好的代码,但请帮助我。我做了我的研究,但这就是我所拥有的。

    import java.util.Arrays;
    import java.util.Scanner;
    public class array {

        public static void main(String[] args) {

    int size;
    int passing;
    Scanner input = new Scanner(System.in);

    System.out.println("Size of Array: ");
    size = input.nextInt();

    System.out.println("Passing Grade: ");
    passing = input.nextInt();

    int [] score = new int [size];
    int [] passed= new int [size];
    int [] failed= new int [size];

    int index = 0;
    int max = 100;
    int min = 50;

    System.out.print("Original List:\n");
    for(int a =0; a<=score.length; a++){
        score[a] = min + (int)(Math.random() * ((max-min) + 1) );
        System.out.print(score[a] + "\n");
    }

    System.out.print("Passed Values:\n");
    for(int a=1; a<=score.length; a++){
        if (score[a] >= passing){
            int res = (passed[index++] = score[a]);
            System.out.print(res + "\n");
        }
    }
    System.out.print("Failed Values:\n");
    for(int a=1; a<=score.length; a++){
        if (score[a] <passing){
            failed[index++] = score[a];
            int res2 = (passed[index++] = score[a]);
            System.out.print(res2 + "\n");
        }
    }
}
    }

1 个答案:

答案 0 :(得分:0)

我发现了三个主要问题,for循环应该检查a<score.length而不是a<=score.length。循环初始条件的第二个和第三个应该是a=0而不是a=1。执行第二个for循环后,您应该将index变量重置为0

public static void main(String[] args) {

            int size;
            int passing;
            Scanner input = new Scanner(System.in);

            System.out.println("Size of Array: ");
            size = input.nextInt();

            System.out.println("Passing Grade: ");
            passing = input.nextInt();

            int [] score = new int [size];
            int [] passed= new int [size];
            int [] failed= new int [size];

            int index = 0;
            int max = 100;
            int min = 50;

            System.out.print("Original List:\n");
            for(int a =0; a<score.length; a++){
                score[a] = min + (int)(Math.random() * ((max-min) + 1) );
                System.out.print(score[a] + "\n");
            }

            System.out.print("Passed Values:\n");
            for(int a=0; a<score.length; a++){
                if (score[a] >= passing){
                    int res = (passed[index++] = score[a]);
                    System.out.print(res + "\n");
                }
            }
            System.out.print("Failed Values:\n");
            index = 0;
            for(int a=0; a<score.length; a++){
                if (score[a] <passing){
                    failed[index++] = score[a];
                    int res2 = (passed[index++] = score[a]);
                    System.out.print(res2 + "\n");
                }
            }
        }