簡體   English   中英

隨機數和冒泡排序

[英]Random numbers and bubble sort

我正在嘗試編寫一個小程序,該程序將允許用戶首先輸入9到18之間的數字,以生成相應的隨機數(代表半徑),然后計算每個隨機生成的數的表面(圓) ,最后按降序對結果進行排序。

到目前為止,這是我的代碼:

import java.util.Scanner;
import java.math.*;
public class test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number from 9 to 18: ");
        int num9a18 = input.nextInt();
        if (num9a18 < 9 || num9a18 > 18) {
            System.out.println("This number is invalid!");
        }       
        int num;
        for (int i = 0; i < num9a18; i++) {
            num = randomInt(1, 6);
            System.out.print(num + " ");
        }
    }
    public static int randomInt(int small, int big) {
        double PI = 3.141592564; 
        int results = ((int) (Math.random() * (big - small + 1)) + small);
        return results*results*PI;
    }
} 

您能給我一些提示嗎,因為我有點卡在這里。

由於int您的程序將出現編譯錯誤- double不一致

修改了程序以解決此問題,以及可能正在尋找的程序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number from 9 to 18: ");
        int num9a18 = input.nextInt();
        if (num9a18 < 9 || num9a18 > 18) {
            System.out.println("This number is invalid!");
        }
        double result;
        List<Double> results = new ArrayList<Double>();
        for (int i = 0; i < num9a18; i++) {
            result = resultFromRandomRadius(1, 6);
            results.add(result);
        }
        System.out.println("................SORTING.................");
        Collections.sort(results);
        for (double res : results) {
            System.out.println(res);
        }
        System.out.println("..........................................");
        System.out.println("................REVERSING.................");
        Collections.reverse(results);
        for (double res : results) {
            System.out.println(res);
        }
    }

    public static double resultFromRandomRadius(int small, int big) {
        double PI = 3.141592564;
        int results = ((int) (Math.random() * (big - small + 1)) + small);
        return results * results * PI;
    }
}

注意:自Java 1.5開始,我正在使用受支持的自動裝箱功能

更新:更新了代碼以演示反向()

輸出:

輸入一個介於9到18之間的數字:

10

.......排序中.................

3.141592564
3.141592564
12.566370256
12.566370256
28.274333076
78.5398141
78.5398141
78.5398141
113.097332304
113.097332304

........................................................... ........逆轉.................

113.097332304
113.097332304
78.5398141
78.5398141
78.5398141
28.274333076
12.566370256
12.566370256
3.141592564
3.141592564

暫無
暫無

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

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