Ⅰ 如何用java隨機生成一個1000位的數字
在Java中生成一個1000位的隨機數,可以使用Random類。首先,我們需要創建一個長度為1000的char數組來存儲隨機數的每一位。接下來,我們通過Random類生成0到9之間的隨機整數,並將其轉換為字元形式,然後依次填充到數組中。具體實現代碼如下:
java
import java.util.Random;
public class BigRandomNumber {
/**
* 生成一個1000位的隨機數,用字元串表示
* @return 返回生成的1000位的隨機數
*/
public static String create() {
char[] num = new char[1000]; // 生成一個1000位的char數組
Random ran = new Random(); // 隨機數類
int temp; // 存放當前隨機數
char cur; // 存放當前字元
for (int i = 0; i < num.length; i++) {
temp = ran.nextInt(10); // 生成一個0-9的隨機數
cur = (char) ('0' + temp); // 轉化成char型的數字
num[i] = cur; // 放到數組的當前位
}
return new String(num); // 返回這個隨機數(用字元串形式)
}
public static void main(String[] args) {
String num = create(); // 生成
System.err.println(num); // 列印驗證
System.err.println(num.length()); // 檢測長度
}
}
在主方法中,我們調用create()方法生成隨機數,並通過System.err.println()列印出來以驗證生成的隨機數。同時,我們還通過num.length()方法檢查生成的隨機數是否確實有1000位。
Ⅱ java用循環編寫一個計數程序輸入幾個數字直到輸入0為止,計算輸入的這些數的平均數
參考代碼如下:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
while(true){
int num = sc.nextInt();
if(num == 0) break;
sum += num;
count++;
}
System.out.println("平均值:"+sum*1.0/count);
}
}
運行結果: