繁体   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