![](/img/trans.png)
[英]How do you print a specific line of text from a text file using math.random in Java?
[英]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.