简体   繁体   English

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

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

I want to basically output 10 numbers per line separated by comma from 0 up to 100 (inclusively).我想基本上每行输出 10 个数字,用逗号分隔,从 0 到 100(含)。 This has to be done only using the Math.random() method, and no other methods at all.这必须仅使用 Math.random() 方法完成,而根本不需要其他方法。 Also, I need to put it in an array.另外,我需要把它放在一个数组中。 This is what I tried so far:这是我到目前为止尝试过的:

// 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]+" ,");
      }
    }
   }
 }

My Output: enter image description here我的输出:在此处输入图像描述

// 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] + " ,");
        } 
    }
  }
 }

As requested.按照要求。

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