簡體   English   中英

java - 如何在java中使用Math.random()每行打印10個數字?

[英]How to print 10 numbers per line using Math.random() in java?

我想基本上每行輸出 10 個數字,用逗號分隔,從 0 到 100(含)。 這必須僅使用 Math.random() 方法完成,而根本不需要其他方法。 另外,我需要把它放在一個數組中。 這是我到目前為止嘗試過的:

// Create class and method
class Main {
public static void main(String[] args) {

// Assign a int array and set the limit to 100
int[] numbers = new int[100];

// Create a for loop to output numbers upto 100
  for (int x = 0; x < numbers.length; x++){
    for (int i = 0; i < 10; i++){

    // Use Math.random() to output random integers, and use typecasting to convert double into int
    numbers[x] = (int)(Math.random()*100);
    System.out.print(numbers[x]+" ,");
      }
    }
   }
 }

我的輸出:在此處輸入圖像描述

// Create class and method
class Main {
public static void main(String[] args) {

    int[] numbers = new int[100];

    for (int x = 0; x < numbers.length; x++){
        numbers[x] = (int) (Math.random() * 101);
        if(((x+1)%10) == 0){
          System.out.println(numbers[x]);
        }else{
          System.out.print(numbers[x] + " ,");
        } 
    }
  }
 }

按照要求。

int[] numbers = new int[100];

// Create a for loop to output numbers upto 100
int i = 0;
for (int x = 0; x < numbers.length; x++) {
    // Use Math.random() to output random integers, and use typecasting to convert
    // double into int
    numbers[x] = (int) (Math.random() * 100);
    System.out.print(numbers[x] + " ,");
    i++;
    if (i == 10) {
        System.out.println();
        i = 0;
    }
}

暫無
暫無

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

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