简体   繁体   中英

How to check to see if an array index has already been called in java

I am making a sample program that randomly assigns a certain amount of students from a certain amount of students to take a survey using arrays. Since a student can't be chosen two times, I need to figure out a way (the most efficient way, of course), to check and make sure that doesn't happen without using ArrayLists. Here is my current code (also if you have any suggestions on how to condense this code, I would love to hear them):

import java.util.*;

 public class StudentsForSurvey {
    public static void main(String[] argv) {
        Scanner kb = new Scanner(System.in);
        Random rndm = new Random();
        int N = 0;
        int slctd = 0;

        while (N < 20) {
            System.out.print("How many students are in the class?");
            N = kb.nextInt();
            System.out.println("Sorry, but School records say that there are at least 20 students           `enter code here`in each classroom. Don't you know your own attendance!?");
    }
    while (slctd > 10 && slctd < 1) {
        System.out.print("\nHow many students to randomly select?");
        slctd = kb.nextInt();
        System.out.println("Sorry, but at least 1 student and at most, 10 students, can    `enter code here`participate in this survey. Didn't someone tell you this at orientation!?");
    }
    int[] stdntnums = new int[slctd - 1];
    for (int i = 0; i < slctd - 1; i++) {
        stdntnums[i] = i + 1;
    }
    int[] help = stdntnums;
    System.out.print("Students selected are: ");
    for (int x = 0; x <= slctd; x++) {
        int rnd = rndm.nextInt(N) - 1;
        for (int z = 0; z <= N; z++) {
            System.out.print(stdntnums[rnd]);
        }
    }
}
}

Try this code. I had to do similar task then i had used it.

java.util.Random r = new java.util.Random();
    java.util.Scanner  s = new java.util.Scanner(System.in);
    int arraylength = s.nextInt();
    int students[] = new int[arraylength];
    for(int i =0;i< arraylength;i++)
    {
        students[i]=i;
        System.out.println(students[i]);
    }
    System.out.println("generated");
    int no_of_selected_students = r.nextInt(arraylength);
    int selected_students[] = new int[no_of_selected_students];
    int last =no_of_selected_students;
    for(int i=0;i<no_of_selected_students;i++)
    {
        int current = r.nextInt(last);
        selected_students[i] = students[current];
        students[current]= students[last];
        last--;
        System.out.println(selected_students[i]);
    }
    System.out.println("randomized");

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