簡體   English   中英

如何將隨機值放入Java數組中?

[英]How can I put my random values into an array in java?

我正在編寫一個對一組整數使用選擇排序的程序,但我通過允許用戶詢問要排序的整數個數以及是否要輸入整數或想要整數來使它更好隨機生成。 到目前為止,我已經對該程序進行了編碼以能夠生成隨機整數,但是我還沒有讓用戶能夠生成自己的數字。

如何獲取那些隨機生成的數字,並將其放入數組中,以便可以對這些值使用選擇排序?

package sortingexcersices;

import java.util.Scanner;
import java.util.Random;

public class SortingExcersices {

    public static int myarray[], numOfElements, arrValues, n;

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("How many integers do you want to sort?");
        numOfElements = in.nextInt();

        myarray = new int[numOfElements];

        boolean found = false;

        do {

            System.out.println("If you would like random numbers, press 1.");
            System.out.println("If you would like to generate your own numbers, press 2.");

            n = in.nextInt();

            if (n == 1) {
                found = true;
            } else if (n == 2) {
                found = false;
            } else {
                System.out.println("Your input was invalid.");
            }

        } while (n != 1 && n != 2);

        if (found = true) {
            Random values = new Random();

            for (int i = 1; i <= myarray.length; i++) {
                arrValues = 1 + values.nextInt(50);
                System.out.print(arrValues + " ,");


            }
        }

    }
}

數組在Java中為零索引...您的for循環應從int i = 0 然后,您可以分配值:

Random values = new Random();
for (int i = 0; i < myarray.length; i++) {
    myarray[i] = values.nextInt(50);
}

然后通過調用Arrays.sort(myarray)或通過實現自定義排序功能(如有必要Arrays.sort(myarray)來實現排序。

for(int i = 0; i < myarray.length; i++){
 myarray[i] = 1 + values.nextInt(50);
 System.out.print(myarray[i] + " ,");
}
for (int i = 1; i <= myarray.length; i++) {
    arrValues[i] = 1 + values.nextInt(50); //you have to add the position
    System.out.print(arrValues + " ,");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM