随机数和冒泡排序

时间:2014-11-12 20:05:18

标签: java random user-input 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;
    }
} 

你可以给我一些提示,因为我有点被困在这里。

1 个答案:

答案 0 :(得分:0)

由于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以来支持的自动装箱功能

更新:更新了代码以演示reverse()以及

<强>输出:

输入9到18之间的数字:

10

................分拣.................

3.141592564
3.141592564
12.566370256
12.566370256
28.274333076
78.5398141
78.5398141
78.5398141
113.097332304
113.097332304

.......................................... ................ REVERSING .................

113.097332304
113.097332304
78.5398141
78.5398141
78.5398141
28.274333076
12.566370256
12.566370256
3.141592564
3.141592564