samedi 25 février 2017

Generating a random number in a loop

I'd like to know how would you generate a random numbers in the loop. I know I should use java.util.random, but i'd like to know how should I do it,because the thing is, that I need to generate as many item random numbers the program needs, because its sorting algorithm.

For example, first of all, you need to choose which method are you using (eg. 1), after that when you input number, the next you need to input count items (eg. 5), and after that, you need to enter items (so if you have 5 items, you need to enter 5 different items and after that sorting will happen.

I need to generate these numbers because if I need to have for example 10000 count I don't want to enter manually 10k of numbers so it would be nice to make it automatically.

Hopefully you can help me! Sorry if i'm wrong or anything, it's my first post here. :)

p.s. I added the part of code here so you can see my loop.

public static void main(String[] args) { //3.part - array output

    int numurs;

        int metode;
        System.out.println("Name Surname RDBF0 student no");
        System.out.print("method: ");

        Scanner sc = new Scanner(System.in);
        if (sc.hasNextInt()){
            numurs = sc.nextInt();
        } 
        else
        {
            System.out.println("input-output error");
            sc.close();
            return;
        }

        if (numurs != 1 && numurs != 2) {
            System.out.println("input-output error");
                sc.close();
                return;
        }



        System.out.print("count: ");
            if (sc.hasNextInt())
                metode = sc.nextInt();

            else {
                System.out.println("input-output error");
                sc.close();
                return;
            }


        int a[] = new int[metode];

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

        for (int i = 0; i < a.length; i++) {

            if (sc.hasNextInt())
            a[i] = sc.nextInt();

        else {
            System.out.println("input-output error");
            sc.close();
            return;
            }
        }
        sc.close();      

        switch (numurs) {

        case 1: firstMethod(a);
        break;
        case 2: secondMethod(a);
        break;

        default:
            System.out.println("input-output error");
        return;
        }
        System.out.println("sorted: ");

            for (int i = 0; i < a.length; i++)
                System.out.print(a[i] + " ");
        } 
    }




Aucun commentaire:

Enregistrer un commentaire