java编写第一题:将一个输入位数不确定的正整数按三位分解格式输出 第二题:使用随机的20个正整数

2025-03-03 05:49:09
推荐回答(2个)
回答1:

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

public class Test {
public static void main(String[] args) throws Exception {
int[] a=new int[20];
for (int i = 0; i < 20; i++) {
a[i]=(int)((Math.random() * 9 + 1) * 1000);
}
int[] b=sort(a);
}
public static int[] sort(int[] arr){
List list=new ArrayList();
for (int i : arr) {
list.add(i);
}
Collections.sort(list, new Comparator() {

@Override
public int compare(Integer o1, Integer o2) {
o1=Integer.parseInt(o1.toString().substring(1));
o2=Integer.parseInt(o2.toString().substring(1));
// TODO Auto-generated method stub
return o1-o2;
}
});
int[] b=new int[10];
for (int i = 0; i < b.length; i++) {
b[i]=list.get(i);
}
return b;
}
}

1.String number=new DecimalFormat("#,###").format(sz);

回答2:

package com.wenxy.test.baidu.zhidao.bank;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Test {

    // 将num分为k个数保存到result中
    void splitNum(int num, int k, List result) {
        if (k > 1) {
            result.add(num % 10);
            splitNum(num / 10, k - 1, result);
        } else {
            result.add(num);
            System.out.print("result: ");
            for (Integer integer : result) {
                System.out.print(integer + "\t");
            }
            System.out.println();
        }
    }

    void sort() {
        int[] a = new int[20];
        Random random = new Random();
        System.out.print("a: ");
        for (int i = 0; i < a.length; i++) {
            a[i] = random.nextInt(8999) + 1000;
            System.out.print(a[i] + "\t");
        }
        System.out.println();

        int[] c = new int[10];
        for (int i = 0; i < c.length; i++) {
            c[i] = a[i] % 1000;
        }

        // sort 使用冒泡排序优化版,没有用collections
        int flag = c.length; // 最后一次交换位置的标识,意味着后面已经有序
        while (flag > 0) {
            int k = flag;
            flag = 0;
            for (int j = 0; j < k - 1; j++) {
                if (c[j] > c[j + 1]) {
                    flag = j + 1;

                    int temp = c[j];
                    c[j] = c[j + 1];
                    c[j + 1] = temp;
                }

            }
        }

        int[] b = new int[10];
        System.out.print("b: ");
        for (int i = 0; i < b.length; i++) {
            b[i] = c[i];
            System.out.print(b[i] + "\t");
        }

    }

    public static void main(String[] args) {
        Test test = new Test();
        test.splitNum(4546, 3, new ArrayList());
        test.sort();
    }
}