簡體   English   中英

Java:使用for循環生成隨機的3位數字

[英]Java: Generating a random 3 digit number using a for loop

我需要使用for循環為項目生成一個隨機的3位數字,但是完全卡住了。 這就是我所擁有的。

    for(int counter = 0; counter < 3; counter++){
        randNum = r.nextInt(9 - 9 + 1) + 9;
        System.out.println(singleNum1);
    }

我知道通常如何使用for循環,而不是生成數字。 每個數字必須分開,然后拼湊在一起。 我將如何去做?

您可以以不同的方式執行此操作,但是這里的主要信息是在開始使用它們進行編碼之前,請先檢查您正在使用的方法及其工作方式。

如果方法的使用很復雜,請使用簡單的算法,然后嘗試對其進行優化。

這是一個方法:

    Random r = new Random();
    String output = "";
    for (int i = 0 ; i < 3 ; i++){
        output+=r.nextInt(10);
    }
    int outputInt = Integer.parseInt(output);

這是第二個:

    Random r = new Random();
    int output = 0;
    for (int i = 0 ; i < 3 ; i++){
        output+=(r.nextInt(10)*Math.pow(10, i));
    }
    System.out.println(output);

暫無
暫無

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

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